1 /* pr -- convert text files for printing.
2 Copyright (C) 88, 91, 1995-2009 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 sturctur 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 has been redefined with the object of a
96 better POSIX compliance. The output of some further cases has been
97 adapted to other UNIXes. A violation of downward compatibility has to
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
314 #include <sys/types.h>
317 #include "mbswidth.h"
319 #include "stat-time.h"
321 #include "strftime.h"
324 /* The official name of this program (e.g., no `g' prefix). */
325 #define PROGRAM_NAME "pr"
328 proper_name ("Pete TerMaat"), \
329 proper_name ("Roland Huebner")
331 /* Used with start_position in the struct COLUMN described below.
332 If start_position == ANYWHERE, we aren't truncating columns and
333 can begin printing a column anywhere. Otherwise we must pad to
334 the horizontal position start_position. */
337 /* Each column has one of these structures allocated for it.
338 If we're only dealing with one file, fp is the same for all
341 The general strategy is to spend time setting up these column
342 structures (storing columns if necessary), after which printing
343 is a matter of flitting from column to column and calling
346 Parallel files, single files printing across in multiple
347 columns, and single files printing down in multiple columns all
348 fit the same printing loop.
350 print_func Function used to print lines in this column.
351 If we're storing this column it will be
352 print_stored(), Otherwise it will be read_line().
354 char_func Function used to process characters in this column.
355 If we're storing this column it will be store_char(),
356 otherwise it will be print_char().
358 current_line Index of the current entry in line_vector, which
359 contains the index of the first character of the
360 current line in buff[].
362 lines_stored Number of lines in this column which are stored in
365 lines_to_print If we're storing this column, lines_to_print is
366 the number of stored_lines which remain to be
367 printed. Otherwise it is the number of lines
368 we can print without exceeding lines_per_body.
370 start_position The horizontal position we want to be in before we
371 print the first character in this column.
373 numbered True means precede this column with a line number. */
375 /* FIXME: There are many unchecked integer overflows in this file,
376 that will cause this command to misbehave given large inputs or
377 options. Many of the "int" values below should be "size_t" or
378 something else like that. */
383 FILE *fp
; /* Input stream for this column. */
384 char const *name
; /* File name. */
388 FF_FOUND
, /* used with -b option, set with \f, changed
389 to ON_HOLD after print_header */
390 ON_HOLD
, /* Hit a form feed. */
393 status
; /* Status of the file pointer. */
395 /* Func to print lines in this col. */
396 bool (*print_func
) (struct COLUMN
*);
398 /* Func to print/store chars in this col. */
399 void (*char_func
) (char);
401 int current_line
; /* Index of current place in line_vector. */
402 int lines_stored
; /* Number of lines stored in buff. */
403 int lines_to_print
; /* No. lines stored or space left on page. */
404 int start_position
; /* Horizontal position of first char. */
406 bool full_page_printed
; /* True means printed without a FF found. */
408 /* p->full_page_printed controls a special case of "FF set by hand":
409 True means a full page has been printed without FF found. To avoid an
410 additional empty page we have to ignore a FF immediately following in
414 typedef struct COLUMN COLUMN
;
416 static int char_to_clump (char c
);
417 static bool read_line (COLUMN
*p
);
418 static bool print_page (void);
419 static bool print_stored (COLUMN
*p
);
420 static bool open_file (char *name
, COLUMN
*p
);
421 static bool skip_to_page (uintmax_t page
);
422 static void print_header (void);
423 static void pad_across_to (int position
);
424 static void add_line_number (COLUMN
*p
);
425 static void getoptarg (char *arg
, char switch_char
, char *character
,
427 void usage (int status
);
428 static void print_files (int number_of_files
, char **av
);
429 static void init_parameters (int number_of_files
);
430 static void init_header (char const *filename
, int desc
);
431 static bool init_fps (int number_of_files
, char **av
);
432 static void init_funcs (void);
433 static void init_store_cols (void);
434 static void store_columns (void);
435 static void balance (int total_stored
);
436 static void store_char (char c
);
437 static void pad_down (int lines
);
438 static void read_rest_of_line (COLUMN
*p
);
439 static void skip_read (COLUMN
*p
, int column_number
);
440 static void print_char (char c
);
441 static void cleanup (void);
442 static void print_sep_string (void);
443 static void separator_string (const char *optarg_S
);
445 /* All of the columns to print. */
446 static COLUMN
*column_vector
;
448 /* When printing a single file in multiple downward columns,
449 we store the leftmost columns contiguously in buff.
450 To print a line from buff, get the index of the first character
451 from line_vector[i], and print up to line_vector[i + 1]. */
454 /* Index of the position in buff where the next character
456 static unsigned int buff_current
;
458 /* The number of characters in buff.
459 Used for allocation of buff and to detect overflow of buff. */
460 static size_t buff_allocated
;
462 /* Array of indices into buff.
463 Each entry is an index of the first character of a line.
464 This is used when storing lines to facilitate shuffling when
465 we do column balancing on the last page. */
466 static int *line_vector
;
468 /* Array of horizonal positions.
469 For each line in line_vector, end_vector[line] is the horizontal
470 position we are in after printing that line. We keep track of this
471 so that we know how much we need to pad to prepare for the next
473 static int *end_vector
;
475 /* (-m) True means we're printing multiple files in parallel. */
476 static bool parallel_files
= false;
478 /* (-m) True means a line starts with some empty columns (some files
479 already CLOSED or ON_HOLD) which we have to align. */
480 static bool align_empty_cols
;
482 /* (-m) True means we have not yet found any printable column in a line.
483 align_empty_cols = true has to be maintained. */
484 static bool empty_line
;
486 /* (-m) False means printable column output precedes a form feed found.
487 Column alignment is done only once. No additional action with that form
489 True means we found only a form feed in a column. Maybe we have to do
490 some column alignment with that form feed. */
493 /* (-[0-9]+) True means we're given an option explicitly specifying
494 number of columns. Used to detect when this option is used with -m
495 and when translating old options to new/long options. */
496 static bool explicit_columns
= false;
498 /* (-t|-T) False means we aren't printing headers and footers. */
499 static bool extremities
= true;
501 /* (-t) True means we retain all FF set by hand in input files.
502 False is set with -T option. */
503 static bool keep_FF
= false;
504 static bool print_a_FF
= false;
506 /* True means we need to print a header as soon as we know we've got input
507 to print after it. */
508 static bool print_a_header
;
510 /* (-f) True means use formfeeds instead of newlines to separate pages. */
511 static bool use_form_feed
= false;
513 /* True means we have read the standard input. */
514 static bool have_read_stdin
= false;
516 /* True means the -a flag has been given. */
517 static bool print_across_flag
= false;
519 /* True means we're printing one file in multiple (>1) downward columns. */
520 static bool storing_columns
= true;
522 /* (-b) True means balance columns on the last page as Sys V does. */
523 /* That's no longer an independent option. With storing_columns = true
524 balance_columns = true is used too (s. function init_parameters).
525 We get a consistent formulation with "FF set by hand" in input files. */
526 static bool balance_columns
= false;
528 /* (-l) Number of lines on a page, including header and footer lines. */
529 static int lines_per_page
= 66;
531 /* Number of lines in the header and footer can be reset to 0 using
533 enum { lines_per_header
= 5 };
534 static int lines_per_body
;
535 enum { lines_per_footer
= 5 };
537 /* (-w|-W) Width in characters of the page. Does not include the width of
539 static int chars_per_line
= 72;
541 /* (-w|W) True means we truncate lines longer than chars_per_column. */
542 static bool truncate_lines
= false;
544 /* (-J) True means we join lines without any line truncation. -J
545 dominates -w option. */
546 static bool join_lines
= false;
548 /* Number of characters in a column. Based on col_sep_length and
550 static int chars_per_column
;
552 /* (-e) True means convert tabs to spaces on input. */
553 static bool untabify_input
= false;
555 /* (-e) The input tab character. */
556 static char input_tab_char
= '\t';
558 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
559 where the leftmost column is 1. */
560 static int chars_per_input_tab
= 8;
562 /* (-i) True means convert spaces to tabs on output. */
563 static bool tabify_output
= false;
565 /* (-i) The output tab character. */
566 static char output_tab_char
= '\t';
568 /* (-i) The width of the output tab. */
569 static int chars_per_output_tab
= 8;
571 /* Keeps track of pending white space. When we hit a nonspace
572 character after some whitespace, we print whitespace, tabbing
573 if necessary to get to output_position + spaces_not_printed. */
574 static int spaces_not_printed
;
576 /* (-o) Number of spaces in the left margin (tabs used when possible). */
577 static int chars_per_margin
= 0;
579 /* Position where the next character will fall.
580 Leftmost position is 0 + chars_per_margin.
581 Rightmost position is chars_per_margin + chars_per_line - 1.
582 This is important for converting spaces to tabs on output. */
583 static int output_position
;
585 /* Horizontal position relative to the current file.
586 (output_position depends on where we are on the page;
587 input_position depends on where we are in the file.)
588 Important for converting tabs to spaces on input. */
589 static int input_position
;
591 /* True if there were any failed opens so we can exit with nonzero
593 static bool failed_opens
= false;
595 /* The number of spaces taken up if we print a tab character with width
596 c_ from position h_. */
597 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
599 /* The horizontal position we'll be at after printing a tab character
600 of width c_ from the position h_. */
601 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
603 /* (-NNN) Number of columns of text to print. */
604 static int columns
= 1;
606 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
607 first_page_number = 0 will be used to check input only. */
608 static uintmax_t first_page_number
= 0;
609 static uintmax_t last_page_number
= UINTMAX_MAX
;
611 /* Number of files open (not closed, not on hold). */
612 static int files_ready_to_read
= 0;
614 /* Current page number. Displayed in header. */
615 static uintmax_t page_number
;
617 /* Current line number. Displayed when -n flag is specified.
619 When printing files in parallel (-m flag), line numbering is as follows:
623 When printing files across (-a flag), ...
627 Otherwise, line numbering is as follows:
630 static int line_number
;
632 /* With line_number overflow, we use power_10 to cut off the higher-order
633 digits of the 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
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. */
733 COLUMNS_OPTION
= CHAR_MAX
+ 1,
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
},
771 /* Return the number of columns that have either an open file or
775 cols_ready_to_print (void)
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))
790 /* Estimate first_ / last_page_number
791 using option +FIRST_PAGE:LAST_PAGE */
794 first_last_page (int oi
, char c
, char const *pages
)
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
)
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
)
819 first_page_number
= first
;
820 last_page_number
= last
;
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 and return true.
827 Otherwise, exit with a diagnostic. */
829 parse_column_count (char const *s
)
832 if (xstrtol (s
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
833 || !(1 <= tmp_long
&& tmp_long
<= INT_MAX
))
834 error (EXIT_FAILURE
, 0,
835 _("invalid number of columns: %s"), quote (s
));
838 explicit_columns
= true;
841 /* Estimate length of col_sep_string with option -S. */
844 separator_string (const char *optarg_S
)
846 col_sep_length
= (int) strlen (optarg_S
);
847 col_sep_string
= xmalloc (col_sep_length
+ 1);
848 strcpy (col_sep_string
, optarg_S
);
852 main (int argc
, char **argv
)
855 bool old_options
= false;
860 /* Accumulate the digits of old-style options like -99. */
861 char *column_count_string
= NULL
;
865 initialize_main (&argc
, &argv
);
866 set_program_name (argv
[0]);
867 setlocale (LC_ALL
, "");
868 bindtextdomain (PACKAGE
, LOCALEDIR
);
869 textdomain (PACKAGE
);
871 atexit (close_stdout
);
874 file_names
= (argc
> 1
875 ? xmalloc ((argc
- 1) * sizeof (char *))
881 int c
= getopt_long (argc
, argv
, short_options
, long_options
, &oi
);
887 /* Accumulate column-count digits specified via old-style options. */
888 if (n_digits
+ 1 >= n_alloc
)
890 = X2REALLOC (column_count_string
, &n_alloc
);
891 column_count_string
[n_digits
++] = c
;
892 column_count_string
[n_digits
] = '\0';
900 case 1: /* Non-option argument. */
901 /* long option --page dominates old `+FIRST_PAGE ...'. */
902 if (! (first_page_number
== 0
903 && *optarg
== '+' && first_last_page (-2, '+', optarg
+ 1)))
904 file_names
[n_files
++] = optarg
;
907 case PAGES_OPTION
: /* --pages=FIRST_PAGE[:LAST_PAGE] */
908 { /* dominates old opt +... */
910 error (EXIT_FAILURE
, 0,
911 _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
912 else if (! first_last_page (oi
, 0, optarg
))
913 error (EXIT_FAILURE
, 0, _("invalid page range %s"),
918 case COLUMNS_OPTION
: /* --columns=COLUMN */
920 parse_column_count (optarg
);
922 /* If there was a prior column count specified via the
923 short-named option syntax, e.g., -9, ensure that this
924 long-name-specified value overrides it. */
925 free (column_count_string
);
926 column_count_string
= NULL
;
932 print_across_flag
= true;
933 storing_columns
= false;
936 balance_columns
= true;
939 use_cntrl_prefix
= true;
945 date_format
= optarg
;
949 getoptarg (optarg
, 'e', &input_tab_char
,
950 &chars_per_input_tab
);
951 /* Could check tab width > 0. */
952 untabify_input
= true;
956 use_form_feed
= true;
959 custom_header
= optarg
;
963 getoptarg (optarg
, 'i', &output_tab_char
,
964 &chars_per_output_tab
);
965 /* Could check tab width > 0. */
966 tabify_output
= true;
974 if (xstrtol (optarg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
975 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
977 error (EXIT_FAILURE
, 0,
978 _("`-l PAGE_LENGTH' invalid number of lines: %s"),
981 lines_per_page
= tmp_long
;
985 parallel_files
= true;
986 storing_columns
= false;
989 numbered_lines
= true;
991 getoptarg (optarg
, 'n', &number_separator
,
998 if (xstrtol (optarg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
999 || tmp_long
> INT_MAX
)
1001 error (EXIT_FAILURE
, 0,
1002 _("`-N NUMBER' invalid starting line number: %s"),
1005 start_line_num
= tmp_long
;
1011 if (xstrtol (optarg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
1012 || tmp_long
< 0 || tmp_long
> INT_MAX
)
1013 error (EXIT_FAILURE
, 0,
1014 _("`-o MARGIN' invalid line offset: %s"), quote (optarg
));
1015 chars_per_margin
= tmp_long
;
1019 ignore_failed_opens
= true;
1024 if (!use_col_separator
&& optarg
)
1025 separator_string (optarg
);
1029 /* Reset an additional input of -s, -S dominates -s */
1030 col_sep_string
= bad_cast ("");
1032 use_col_separator
= true;
1034 separator_string (optarg
);
1037 extremities
= false;
1041 extremities
= false;
1045 use_esc_sequence
= true;
1052 if (xstrtol (optarg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
1053 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1054 error (EXIT_FAILURE
, 0,
1055 _("`-w PAGE_WIDTH' invalid number of characters: %s"),
1057 if (!truncate_lines
)
1058 chars_per_line
= tmp_long
;
1062 old_w
= false; /* dominates -w */
1063 truncate_lines
= true;
1066 if (xstrtol (optarg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
1067 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1068 error (EXIT_FAILURE
, 0,
1069 _("`-W PAGE_WIDTH' invalid number of characters: %s"),
1071 chars_per_line
= tmp_long
;
1074 case_GETOPT_HELP_CHAR
;
1075 case_GETOPT_VERSION_CHAR (PROGRAM_NAME
, AUTHORS
);
1077 usage (EXIT_FAILURE
);
1082 if (column_count_string
)
1084 parse_column_count (column_count_string
);
1085 free (column_count_string
);
1089 date_format
= (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME
)
1091 : "%Y-%m-%d %H:%M");
1093 /* Now we can set a reasonable initial value: */
1094 if (first_page_number
== 0)
1095 first_page_number
= 1;
1097 if (parallel_files
& explicit_columns
)
1098 error (EXIT_FAILURE
, 0,
1099 _("cannot specify number of columns when printing in parallel"));
1101 if (parallel_files
& print_across_flag
)
1102 error (EXIT_FAILURE
, 0,
1103 _("cannot specify both printing across and printing in parallel"));
1105 /* Translate some old short options to new/long options.
1106 To meet downward compatibility with other UNIX pr utilities
1107 and some POSIX specifications. */
1113 if (parallel_files
| explicit_columns
)
1116 truncate_lines
= true;
1118 /* adapt HP-UX and SunOS: -s = no separator;
1120 use_col_separator
= true;
1123 /* old -w sets width with columns only
1127 else if (!use_col_separator
)
1129 /* No -S option read */
1130 if (old_s
& (parallel_files
| explicit_columns
))
1132 if (!truncate_lines
)
1134 /* old -s (without -w and -W) annuls column alignment,
1135 uses fields, activate -J */
1137 if (col_sep_length
> 0)
1139 use_col_separator
= true;
1143 /* adapt HP-UX and SunOS: -s = no separator;
1145 use_col_separator
= true;
1150 for (; optind
< argc
; optind
++)
1152 file_names
[n_files
++] = argv
[optind
];
1157 /* No file arguments specified; read from standard input. */
1158 print_files (0, NULL
);
1163 print_files (n_files
, file_names
);
1167 for (i
= 0; i
< n_files
; i
++)
1168 print_files (1, &file_names
[i
]);
1174 if (have_read_stdin
&& fclose (stdin
) == EOF
)
1175 error (EXIT_FAILURE
, errno
, _("standard input"));
1177 exit (EXIT_FAILURE
);
1178 exit (EXIT_SUCCESS
);
1181 /* Parse options of the form -scNNN.
1183 Example: -nck, where 'n' is the option, c is the optional number
1184 separator, and k is the optional width of the field used when printing
1188 getoptarg (char *arg
, char switch_char
, char *character
, int *number
)
1190 if (!ISDIGIT (*arg
))
1191 *character
= *arg
++;
1195 if (xstrtol (arg
, NULL
, 10, &tmp_long
, "") != LONGINT_OK
1196 || tmp_long
<= 0 || tmp_long
> INT_MAX
)
1199 _("`-%c' extra characters or invalid number in the argument: %s"),
1200 switch_char
, quote (arg
));
1201 usage (EXIT_FAILURE
);
1207 /* Set parameters related to formatting. */
1210 init_parameters (int number_of_files
)
1212 int chars_used_by_number
= 0;
1214 lines_per_body
= lines_per_page
- lines_per_header
- lines_per_footer
;
1215 if (lines_per_body
<= 0)
1217 extremities
= false;
1220 if (extremities
== false)
1221 lines_per_body
= lines_per_page
;
1224 lines_per_body
= lines_per_body
/ 2;
1226 /* If input is stdin, cannot print parallel files. BSD dumps core
1228 if (number_of_files
== 0)
1229 parallel_files
= false;
1232 columns
= number_of_files
;
1234 /* One file, multi columns down: -b option is set to get a consistent
1235 formulation with "FF set by hand" in input files. */
1236 if (storing_columns
)
1237 balance_columns
= true;
1239 /* Tabification is assumed for multiple columns. */
1242 if (!use_col_separator
)
1244 /* Use default separator */
1246 col_sep_string
= line_separator
;
1248 col_sep_string
= column_separator
;
1251 use_col_separator
= true;
1253 /* It's rather pointless to define a TAB separator with column
1255 else if (!join_lines
&& *col_sep_string
== '\t')
1256 col_sep_string
= column_separator
;
1258 truncate_lines
= true;
1259 tabify_output
= true;
1262 storing_columns
= false;
1264 /* -J dominates -w in any case */
1266 truncate_lines
= false;
1271 int chars_per_default_tab
= 8;
1273 line_count
= start_line_num
;
1275 /* To allow input tab-expansion (-e sensitive) use:
1276 if (number_separator == input_tab_char)
1277 number_width = chars_per_number +
1278 TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1280 /* Estimate chars_per_text without any margin and keep it constant. */
1281 if (number_separator
== '\t')
1282 number_width
= chars_per_number
+
1283 TAB_WIDTH (chars_per_default_tab
, chars_per_number
);
1285 number_width
= chars_per_number
+ 1;
1287 /* The number is part of the column width unless we are
1288 printing files in parallel. */
1290 chars_used_by_number
= number_width
;
1292 /* We use power_10 to cut off the higher-order digits of the
1293 line_number in function add_line_number */
1294 tmp_i
= chars_per_number
;
1295 for (power_10
= 1; tmp_i
> 0; --tmp_i
)
1296 power_10
= 10 * power_10
;
1299 chars_per_column
= (chars_per_line
- chars_used_by_number
-
1300 (columns
- 1) * col_sep_length
) / columns
;
1302 if (chars_per_column
< 1)
1303 error (EXIT_FAILURE
, 0, _("page width too narrow"));
1308 number_buff
= xmalloc (2 * chars_per_number
);
1311 /* Pick the maximum between the tab width and the width of an
1313 The width of an escape sequence (4) isn't the lower limit any longer.
1314 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1315 to expand a tab which is not an input_tab-char. */
1317 clump_buff
= xmalloc (MAX (8, chars_per_input_tab
));
1320 /* Open the necessary files,
1321 maintaining a COLUMN structure for each column.
1323 With multiple files, each column p has a different p->fp.
1324 With single files, each column p has the same p->fp.
1325 Return false if (number_of_files > 0) and no files can be opened,
1328 With each column/file p, p->full_page_printed is initialized,
1329 see also open_file. */
1332 init_fps (int number_of_files
, char **av
)
1337 char const *firstname
;
1341 free (column_vector
);
1342 column_vector
= xnmalloc (columns
, sizeof (COLUMN
));
1346 files_left
= number_of_files
;
1347 for (p
= column_vector
; files_left
--; ++p
, ++av
)
1349 if (! open_file (*av
, p
))
1357 init_header ("", -1);
1362 if (number_of_files
> 0)
1364 if (! open_file (*av
, p
))
1366 init_header (*av
, fileno (p
->fp
));
1367 p
->lines_stored
= 0;
1371 p
->name
= _("standard input");
1373 have_read_stdin
= true;
1375 p
->full_page_printed
= false;
1377 init_header ("", -1);
1378 p
->lines_stored
= 0;
1381 firstname
= p
->name
;
1383 for (i
= columns
- 1, ++p
; i
; --i
, ++p
)
1385 p
->name
= firstname
;
1388 p
->full_page_printed
= false;
1389 p
->lines_stored
= 0;
1392 files_ready_to_read
= total_files
;
1396 /* Determine print_func and char_func, the functions
1397 used by each column for printing and/or storing.
1399 Determine the horizontal position desired when we begin
1400 printing a column (p->start_position). */
1408 h
= chars_per_margin
;
1410 if (!truncate_lines
)
1414 /* When numbering lines of parallel files, we enlarge the
1415 first column to accomodate the number. Looks better than
1416 the Sys V approach. */
1417 if (parallel_files
& numbered_lines
)
1418 h_next
= h
+ chars_per_column
+ number_width
;
1420 h_next
= h
+ chars_per_column
;
1423 /* Enlarge p->start_position of first column to use the same form of
1424 padding_not_printed with all columns. */
1425 h
= h
+ col_sep_length
;
1427 /* This loop takes care of all but the rightmost column. */
1429 for (p
= column_vector
, i
= 1; i
< columns
; ++p
, ++i
)
1431 if (storing_columns
) /* One file, multi columns down. */
1433 p
->char_func
= store_char
;
1434 p
->print_func
= print_stored
;
1437 /* One file, multi columns across; or parallel files. */
1439 p
->char_func
= print_char
;
1440 p
->print_func
= read_line
;
1443 /* Number only the first column when printing files in
1445 p
->numbered
= numbered_lines
&& (!parallel_files
|| i
== 1);
1446 p
->start_position
= h
;
1448 /* If we don't truncate lines, all start_positions are
1449 ANYWHERE, except the first column's start_position when
1452 if (!truncate_lines
)
1459 h
= h_next
+ col_sep_length
;
1460 h_next
= h
+ chars_per_column
;
1464 /* The rightmost column.
1466 Doesn't need to be stored unless we intend to balance
1467 columns on the last page. */
1468 if (storing_columns
& balance_columns
)
1470 p
->char_func
= store_char
;
1471 p
->print_func
= print_stored
;
1475 p
->char_func
= print_char
;
1476 p
->print_func
= read_line
;
1479 p
->numbered
= numbered_lines
&& (!parallel_files
|| i
== 1);
1480 p
->start_position
= h
;
1483 /* Open a file. Return true if successful.
1485 With each file p, p->full_page_printed is initialized,
1486 see also init_fps. */
1489 open_file (char *name
, COLUMN
*p
)
1491 if (STREQ (name
, "-"))
1493 p
->name
= _("standard input");
1495 have_read_stdin
= true;
1500 p
->fp
= fopen (name
, "r");
1504 failed_opens
= true;
1505 if (!ignore_failed_opens
)
1506 error (0, errno
, "%s", name
);
1510 p
->full_page_printed
= false;
1515 /* Close the file in P.
1517 If we aren't dealing with multiple files in parallel, we change
1518 the status of all columns in the column list to reflect the close. */
1521 close_file (COLUMN
*p
)
1526 if (p
->status
== CLOSED
)
1529 error (EXIT_FAILURE
, errno
, "%s", p
->name
);
1530 if (fileno (p
->fp
) != STDIN_FILENO
&& fclose (p
->fp
) != 0)
1531 error (EXIT_FAILURE
, errno
, "%s", p
->name
);
1533 if (!parallel_files
)
1535 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
1538 if (q
->lines_stored
== 0)
1540 q
->lines_to_print
= 0;
1547 p
->lines_to_print
= 0;
1550 --files_ready_to_read
;
1553 /* Put a file on hold until we start a new page,
1554 since we've hit a form feed.
1556 If we aren't dealing with parallel files, we must change the
1557 status of all columns in the column list. */
1560 hold_file (COLUMN
*p
)
1565 if (!parallel_files
)
1566 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
1568 if (storing_columns
)
1569 q
->status
= FF_FOUND
;
1571 q
->status
= ON_HOLD
;
1574 p
->status
= ON_HOLD
;
1576 p
->lines_to_print
= 0;
1577 --files_ready_to_read
;
1580 /* Undo hold_file -- go through the column list and change any
1581 ON_HOLD columns to OPEN. Used at the end of each page. */
1589 for (p
= column_vector
; i
; --i
, ++p
)
1590 if (p
->status
== ON_HOLD
)
1593 files_ready_to_read
++;
1596 if (storing_columns
)
1598 if (column_vector
->status
== CLOSED
)
1599 /* We use the info to output an error message in skip_to_page. */
1600 files_ready_to_read
= 0;
1602 files_ready_to_read
= 1;
1606 /* Print a single file, or multiple files in parallel.
1608 Set up the list of columns, opening the necessary files.
1609 Allocate space for storing columns, if necessary.
1610 Skip to first_page_number, if user has asked to skip leading pages.
1611 Determine which functions are appropriate to store/print lines
1613 Print the file(s). */
1616 print_files (int number_of_files
, char **av
)
1618 init_parameters (number_of_files
);
1619 if (! init_fps (number_of_files
, av
))
1621 if (storing_columns
)
1624 if (first_page_number
> 1)
1626 if (!skip_to_page (first_page_number
))
1629 page_number
= first_page_number
;
1636 line_number
= line_count
;
1637 while (print_page ())
1641 /* Initialize header information.
1642 If DESC is non-negative, it is a file descriptor open to
1643 FILENAME for reading. */
1646 init_header (char const *filename
, int desc
)
1654 /* If parallel files or standard input, use current date. */
1655 if (STREQ (filename
, "-"))
1657 if (0 <= desc
&& fstat (desc
, &st
) == 0)
1658 t
= get_stat_mtime (&st
);
1661 static struct timespec timespec
;
1662 if (! timespec
.tv_sec
)
1663 gettime (×pec
);
1668 tm
= localtime (&t
.tv_sec
);
1671 buf
= xmalloc (INT_BUFSIZE_BOUND (long int)
1672 + MAX (10, INT_BUFSIZE_BOUND (int)));
1673 sprintf (buf
, "%ld.%09d", (long int) t
.tv_sec
, ns
);
1677 size_t bufsize
= nstrftime (NULL
, SIZE_MAX
, date_format
, tm
, 0, ns
) + 1;
1678 buf
= xmalloc (bufsize
);
1679 nstrftime (buf
, bufsize
, date_format
, tm
, 0, ns
);
1684 file_text
= custom_header
? custom_header
: desc
< 0 ? "" : filename
;
1685 header_width_available
= (chars_per_line
1686 - mbswidth (date_text
, 0)
1687 - mbswidth (file_text
, 0));
1690 /* Set things up for printing a page
1692 Scan through the columns ...
1693 Determine which are ready to print
1694 (i.e., which have lines stored or open files)
1695 Set p->lines_to_print appropriately
1696 (to p->lines_stored if we're storing, or lines_per_body
1697 if we're reading straight from the file)
1698 Keep track of this total so we know when to stop printing */
1706 if (storing_columns
)
1709 for (j
= columns
- 1, p
= column_vector
; j
; --j
, ++p
)
1711 p
->lines_to_print
= p
->lines_stored
;
1715 if (balance_columns
)
1717 p
->lines_to_print
= p
->lines_stored
;
1719 /* Since we're not balancing columns, we don't need to store
1720 the rightmost column. Read it straight from the file. */
1723 if (p
->status
== OPEN
)
1725 p
->lines_to_print
= lines_per_body
;
1728 p
->lines_to_print
= 0;
1732 for (j
= columns
, p
= column_vector
; j
; --j
, ++p
)
1733 if (p
->status
== OPEN
)
1735 p
->lines_to_print
= lines_per_body
;
1738 p
->lines_to_print
= 0;
1741 /* Align empty columns and print separators.
1742 Empty columns will be formed by files with status ON_HOLD or CLOSED
1743 when printing multiple files in parallel. */
1746 align_column (COLUMN
*p
)
1748 padding_not_printed
= p
->start_position
;
1749 if (padding_not_printed
- col_sep_length
> 0)
1751 pad_across_to (padding_not_printed
- col_sep_length
);
1752 padding_not_printed
= ANYWHERE
;
1755 if (use_col_separator
)
1756 print_sep_string ();
1759 add_line_number (p
);
1764 As long as there are lines left on the page and columns ready to print,
1765 Scan across the column list
1766 if the column has stored lines or the file is open
1767 pad to the appropriate spot
1769 pad the remainder of the page with \n or \f as requested
1770 reset the status of all files -- any files which where on hold because
1771 of formfeeds are now put back into the lineup. */
1777 int lines_left_on_page
;
1780 /* Used as an accumulator (with | operator) of successive values of
1781 pad_vertically. The trick is to set pad_vertically
1782 to false before each run through the inner loop, then after that
1783 loop, it tells us whether a line was actually printed (whether a
1784 newline needs to be output -- or two for double spacing). But those
1785 values have to be accumulated (in pv) so we can invoke pad_down
1786 properly after the outer loop completes. */
1791 if (cols_ready_to_print () == 0)
1795 print_a_header
= true;
1797 /* Don't pad unless we know a page was printed. */
1798 pad_vertically
= false;
1801 lines_left_on_page
= lines_per_body
;
1803 lines_left_on_page
*= 2;
1805 while (lines_left_on_page
> 0 && cols_ready_to_print () > 0)
1807 output_position
= 0;
1808 spaces_not_printed
= 0;
1809 separators_not_printed
= 0;
1810 pad_vertically
= false;
1811 align_empty_cols
= false;
1814 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
1817 if (p
->lines_to_print
> 0 || p
->status
== FF_FOUND
)
1820 padding_not_printed
= p
->start_position
;
1821 if (!(p
->print_func
) (p
))
1822 read_rest_of_line (p
);
1823 pv
|= pad_vertically
;
1825 --p
->lines_to_print
;
1826 if (p
->lines_to_print
<= 0)
1828 if (cols_ready_to_print () <= 0)
1832 /* File p changed its status to ON_HOLD or CLOSED */
1833 if (parallel_files
&& p
->status
!= OPEN
)
1836 align_empty_cols
= true;
1837 else if (p
->status
== CLOSED
||
1838 (p
->status
== ON_HOLD
&& FF_only
))
1842 else if (parallel_files
)
1844 /* File status ON_HOLD or CLOSED */
1846 align_empty_cols
= true;
1851 /* We need it also with an empty column */
1852 if (use_col_separator
)
1853 ++separators_not_printed
;
1859 --lines_left_on_page
;
1862 if (cols_ready_to_print () <= 0 && !extremities
)
1865 if (double_space
& pv
)
1868 --lines_left_on_page
;
1872 if (lines_left_on_page
== 0)
1873 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
1874 if (p
->status
== OPEN
)
1875 p
->full_page_printed
= true;
1877 pad_vertically
= pv
;
1879 if (pad_vertically
& extremities
)
1880 pad_down (lines_left_on_page
+ lines_per_footer
);
1881 else if (keep_FF
& print_a_FF
)
1887 if (last_page_number
< page_number
)
1888 return false; /* Stop printing with LAST_PAGE */
1890 reset_status (); /* Change ON_HOLD to OPEN. */
1892 return true; /* More pages to go. */
1895 /* Allocate space for storing columns.
1897 This is necessary when printing multiple columns from a single file.
1898 Lines are stored consecutively in buff, separated by '\0'.
1900 The following doesn't apply any longer - any tuning possible?
1901 (We can't use a fixed offset since with the '-s' flag lines aren't
1904 We maintain a list (line_vector) of pointers to the beginnings
1905 of lines in buff. We allocate one more than the number of lines
1906 because the last entry tells us the index of the last character,
1907 which we need to know in order to print the last line in buff. */
1910 init_store_cols (void)
1912 int total_lines
= lines_per_body
* columns
;
1913 int chars_if_truncate
= total_lines
* (chars_per_column
+ 1);
1916 /* FIXME: here's where it was allocated. */
1917 line_vector
= xmalloc ((total_lines
+ 1) * sizeof (int *));
1920 end_vector
= xmalloc (total_lines
* sizeof (int *));
1923 buff_allocated
= (use_col_separator
1924 ? 2 * chars_if_truncate
1925 : chars_if_truncate
); /* Tune this. */
1926 buff
= xmalloc (buff_allocated
);
1929 /* Store all but the rightmost column.
1930 (Used when printing a single file in multiple downward columns)
1933 set p->current_line to be the index in line_vector of the
1934 first line in the column
1935 For each line in the column
1936 store the line in buff
1937 add to line_vector the index of the line's first char
1938 buff_start is the index in buff of the first character in the
1942 store_columns (void)
1945 unsigned int line
= 0;
1946 unsigned int buff_start
;
1947 int last_col
; /* The rightmost column which will be saved in buff */
1953 if (balance_columns
)
1956 last_col
= columns
- 1;
1958 for (i
= 1, p
= column_vector
; i
<= last_col
; ++i
, ++p
)
1959 p
->lines_stored
= 0;
1961 for (i
= 1, p
= column_vector
; i
<= last_col
&& files_ready_to_read
;
1964 p
->current_line
= line
;
1965 for (j
= lines_per_body
; j
&& files_ready_to_read
; --j
)
1967 if (p
->status
== OPEN
) /* Redundant. Clean up. */
1972 read_rest_of_line (p
);
1974 if (p
->status
== OPEN
1975 || buff_start
!= buff_current
)
1978 line_vector
[line
] = buff_start
;
1979 end_vector
[line
++] = input_position
;
1980 buff_start
= buff_current
;
1985 /* Keep track of the location of the last char in buff. */
1986 line_vector
[line
] = buff_start
;
1988 if (balance_columns
)
1993 balance (int total_stored
)
1999 for (i
= 1, p
= column_vector
; i
<= columns
; ++i
, ++p
)
2001 lines
= total_stored
/ columns
;
2002 if (i
<= total_stored
% columns
)
2005 p
->lines_stored
= lines
;
2006 p
->current_line
= first_line
;
2008 first_line
+= lines
;
2012 /* Store a character in the buffer. */
2017 if (buff_current
>= buff_allocated
)
2019 /* May be too generous. */
2020 buff
= X2REALLOC (buff
, &buff_allocated
);
2022 buff
[buff_current
++] = c
;
2026 add_line_number (COLUMN
*p
)
2032 /* Cutting off the higher-order digits is more informative than
2033 lower-order cut off*/
2034 if (line_number
< power_10
)
2035 sprintf (number_buff
, "%*d", chars_per_number
, line_number
);
2038 left_cut
= line_number
% power_10
;
2039 sprintf (number_buff
, "%0*d", chars_per_number
, left_cut
);
2043 for (i
= chars_per_number
; i
> 0; i
--)
2044 (p
->char_func
) (*s
++);
2048 /* Tabification is assumed for multiple columns, also for n-separators,
2049 but `default n-separator = TAB' hasn't been given priority over
2050 equal column_width also specified by POSIX. */
2051 if (number_separator
== '\t')
2053 i
= number_width
- chars_per_number
;
2055 (p
->char_func
) (' ');
2058 (p
->char_func
) (number_separator
);
2061 /* To comply with POSIX, we avoid any expansion of default TAB
2062 separator with a single column output. No column_width requirement
2063 has to be considered. */
2065 (p
->char_func
) (number_separator
);
2066 if (number_separator
== '\t')
2067 output_position
= POS_AFTER_TAB (chars_per_output_tab
,
2071 if (truncate_lines
& !parallel_files
)
2072 input_position
+= number_width
;
2075 /* Print (or store) padding until the current horizontal position
2079 pad_across_to (int position
)
2081 int h
= output_position
;
2084 spaces_not_printed
= position
- output_position
;
2087 while (++h
<= position
)
2089 output_position
= position
;
2093 /* Pad to the bottom of the page.
2095 If the user has requested a formfeed, use one.
2096 Otherwise, use newlines. */
2099 pad_down (int lines
)
2106 for (i
= lines
; i
; --i
)
2110 /* Read the rest of the line.
2112 Read from the current column's file until an end of line is
2113 hit. Used when we've truncated a line and we no longer need
2114 to print or store its characters. */
2117 read_rest_of_line (COLUMN
*p
)
2122 while ((c
= getc (f
)) != '\n')
2126 if ((c
= getc (f
)) != '\n')
2141 /* Read a line with skip_to_page.
2143 Read from the current column's file until an end of line is
2144 hit. Used when we read full lines to skip pages.
2145 With skip_to_page we have to check for FF-coincidence which is done
2146 in function read_line otherwise.
2147 Count lines of skipped pages to find the line number of 1st page
2148 printed relative to 1st line of input file (start_line_num). */
2151 skip_read (COLUMN
*p
, int column_number
)
2156 bool single_ff
= false;
2159 /* Read 1st character in a line or any character succeeding a FF */
2160 if ((c
= getc (f
)) == '\f' && p
->full_page_printed
)
2161 /* A FF-coincidence with a previous full_page_printed.
2162 To avoid an additional empty page, eliminate the FF */
2163 if ((c
= getc (f
)) == '\n')
2166 p
->full_page_printed
= false;
2168 /* 1st character a FF means a single FF without any printable
2169 characters. Don't count it as a line with -n option. */
2173 /* Preparing for a FF-coincidence: Maybe we finish that page
2174 without a FF found */
2176 p
->full_page_printed
= true;
2182 /* No FF-coincidence possible,
2183 no catching up of a FF-coincidence with next page */
2186 if (!parallel_files
)
2187 for (q
= column_vector
, i
= columns
; i
; ++q
, --i
)
2188 q
->full_page_printed
= false;
2190 p
->full_page_printed
= false;
2193 if ((c
= getc (f
)) != '\n')
2207 if ((!parallel_files
|| column_number
== 1) && !single_ff
)
2211 /* If we're tabifying output,
2213 When print_char encounters white space it keeps track
2214 of our desired horizontal position and delays printing
2215 until this function is called. */
2218 print_white_space (void)
2221 int h_old
= output_position
;
2222 int goal
= h_old
+ spaces_not_printed
;
2224 while (goal
- h_old
> 1
2225 && (h_new
= POS_AFTER_TAB (chars_per_output_tab
, h_old
)) <= goal
)
2227 putchar (output_tab_char
);
2230 while (++h_old
<= goal
)
2233 output_position
= goal
;
2234 spaces_not_printed
= 0;
2237 /* Print column separators.
2239 We keep a count until we know that we'll be printing a line,
2240 then print_sep_string() is called. */
2243 print_sep_string (void)
2246 int l
= col_sep_length
;
2250 if (separators_not_printed
<= 0)
2252 /* We'll be starting a line with chars_per_margin, anything else? */
2253 if (spaces_not_printed
> 0)
2254 print_white_space ();
2258 for (; separators_not_printed
> 0; --separators_not_printed
)
2262 /* 3 types of sep_strings: spaces only, spaces and chars,
2266 /* We're tabifying output; consecutive spaces in
2267 sep_string may have to be converted to tabs */
2269 ++spaces_not_printed
;
2273 if (spaces_not_printed
> 0)
2274 print_white_space ();
2279 /* sep_string ends with some spaces */
2280 if (spaces_not_printed
> 0)
2281 print_white_space ();
2286 /* Print (or store, depending on p->char_func) a clump of N
2290 print_clump (COLUMN
*p
, int n
, char *clump
)
2293 (p
->char_func
) (*clump
++);
2296 /* Print a character.
2298 Update the following comment: process-char hasn't been used any
2300 If we're tabifying, all tabs have been converted to spaces by
2301 process_char(). Keep a count of consecutive spaces, and when
2302 a nonspace is encountered, call print_white_space() to print the
2303 required number of tabs and spaces. */
2312 ++spaces_not_printed
;
2315 else if (spaces_not_printed
> 0)
2316 print_white_space ();
2318 /* Nonprintables are assumed to have width 0, except '\b'. */
2319 if (! isprint (to_uchar (c
)))
2330 /* Skip to page PAGE before printing.
2331 PAGE may be larger than total number of pages. */
2334 skip_to_page (uintmax_t page
)
2341 for (n
= 1; n
< page
; ++n
)
2343 for (i
= 1; i
< lines_per_body
; ++i
)
2345 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2346 if (p
->status
== OPEN
)
2350 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2351 if (p
->status
== OPEN
)
2354 if (storing_columns
) /* change FF_FOUND to ON_HOLD */
2355 for (j
= 1, p
= column_vector
; j
<= columns
; ++j
, ++p
)
2356 if (p
->status
!= CLOSED
)
2357 p
->status
= ON_HOLD
;
2362 if (files_ready_to_read
< 1)
2364 /* It's very helpful, normally the total number of pages is
2365 not known in advance. */
2367 _("starting page number %"PRIuMAX
2368 " exceeds page count %"PRIuMAX
),
2373 return files_ready_to_read
> 0;
2378 Formfeeds are assumed to use up two lines at the beginning of
2384 char page_text
[256 + INT_STRLEN_BOUND (page_number
)];
2385 int available_width
;
2389 output_position
= 0;
2390 pad_across_to (chars_per_margin
);
2391 print_white_space ();
2393 if (page_number
== 0)
2394 error (EXIT_FAILURE
, 0, _("page number overflow"));
2396 /* The translator must ensure that formatting the translation of
2397 "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2399 sprintf (page_text
, _("Page %"PRIuMAX
), page_number
++);
2400 available_width
= header_width_available
- mbswidth (page_text
, 0);
2401 available_width
= MAX (0, available_width
);
2402 lhs_spaces
= available_width
>> 1;
2403 rhs_spaces
= available_width
- lhs_spaces
;
2405 printf ("\n\n%*.*s%s%*.*s%s%*.*s%s\n\n\n",
2406 chars_per_margin
, chars_per_margin
, " ",
2407 date_text
, lhs_spaces
, lhs_spaces
, " ",
2408 file_text
, rhs_spaces
, rhs_spaces
, " ", page_text
);
2410 print_a_header
= false;
2411 output_position
= 0;
2414 /* Print (or store, if p->char_func is store_char()) a line.
2416 Read a character to determine whether we have a line or not.
2417 (We may hit EOF, \n, or \f)
2419 Once we know we have a line,
2420 set pad_vertically = true, meaning it's safe
2421 to pad down at the end of the page, since we do have a page.
2422 print a header if needed.
2423 pad across to padding_not_printed if needed.
2424 print any separators which need to be printed.
2425 print a line number if it needs to be printed.
2427 Print the clump which corresponds to the first character.
2429 Enter a loop and keep printing until an end of line condition
2430 exists, or until we exceed chars_per_column.
2432 Return false if we exceed chars_per_column before reading
2433 an end of line character, true otherwise. */
2436 read_line (COLUMN
*p
)
2439 int chars
IF_LINT (= 0);
2440 int last_input_position
;
2444 /* read 1st character in each line or any character succeeding a FF: */
2447 last_input_position
= input_position
;
2449 if (c
== '\f' && p
->full_page_printed
)
2450 if ((c
= getc (p
->fp
)) == '\n')
2452 p
->full_page_printed
= false;
2457 if ((c
= getc (p
->fp
)) != '\n')
2460 if (print_a_header
& !storing_columns
)
2462 pad_vertically
= true;
2475 chars
= char_to_clump (c
);
2478 if (truncate_lines
&& input_position
> chars_per_column
)
2480 input_position
= last_input_position
;
2484 if (p
->char_func
!= store_char
)
2486 pad_vertically
= true;
2488 if (print_a_header
& !storing_columns
)
2491 if (parallel_files
& align_empty_cols
)
2493 /* We have to align empty columns at the beginning of a line. */
2494 k
= separators_not_printed
;
2495 separators_not_printed
= 0;
2496 for (j
= 1, q
= column_vector
; j
<= k
; ++j
, ++q
)
2499 separators_not_printed
+= 1;
2501 padding_not_printed
= p
->start_position
;
2503 spaces_not_printed
= chars_per_column
;
2505 spaces_not_printed
= 0;
2506 align_empty_cols
= false;
2509 if (padding_not_printed
- col_sep_length
> 0)
2511 pad_across_to (padding_not_printed
- col_sep_length
);
2512 padding_not_printed
= ANYWHERE
;
2515 if (use_col_separator
)
2516 print_sep_string ();
2520 add_line_number (p
);
2526 print_clump (p
, chars
, clump_buff
);
2537 if ((c
= getc (p
->fp
)) != '\n')
2548 last_input_position
= input_position
;
2549 chars
= char_to_clump (c
);
2550 if (truncate_lines
&& input_position
> chars_per_column
)
2552 input_position
= last_input_position
;
2556 print_clump (p
, chars
, clump_buff
);
2560 /* Print a line from buff.
2562 If this function has been called, we know we have "something to
2563 print". But it remains to be seen whether we have a real text page
2564 or an empty page (a single form feed) with/without a header only.
2565 Therefore first we set pad_vertically to true and print a header
2567 If FF_FOUND and we are using -t|-T option we omit any newline by
2568 setting pad_vertically to false (see print_page).
2569 Otherwise we pad across if necessary, print separators if necessary
2570 and text of COLUMN *p.
2572 Return true, meaning there is no need to call read_rest_of_line. */
2575 print_stored (COLUMN
*p
)
2580 int line
= p
->current_line
++;
2581 char *first
= &buff
[line_vector
[line
]];
2583 UMR: Uninitialized memory read:
2584 * This is occurring while in:
2585 print_stored [pr.c:2239]
2586 * Reading 4 bytes from 0x5148c in the heap.
2587 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2588 * This block was allocated from:
2590 xmalloc [xmalloc.c:94]
2591 init_store_cols [pr.c:1648]
2593 char *last
= &buff
[line_vector
[line
+ 1]];
2595 pad_vertically
= true;
2600 if (p
->status
== FF_FOUND
)
2602 for (i
= 1, q
= column_vector
; i
<= columns
; ++i
, ++q
)
2603 q
->status
= ON_HOLD
;
2604 if (column_vector
->lines_to_print
<= 0)
2607 pad_vertically
= false;
2608 return true; /* print a header only */
2612 if (padding_not_printed
- col_sep_length
> 0)
2614 pad_across_to (padding_not_printed
- col_sep_length
);
2615 padding_not_printed
= ANYWHERE
;
2618 if (use_col_separator
)
2619 print_sep_string ();
2621 while (first
!= last
)
2622 print_char (*first
++);
2624 if (spaces_not_printed
== 0)
2626 output_position
= p
->start_position
+ end_vector
[line
];
2627 if (p
->start_position
- col_sep_length
== chars_per_margin
)
2628 output_position
-= col_sep_length
;
2634 /* Convert a character to the proper format and return the number of
2635 characters in the resulting clump. Increment input_position by
2636 the width of the clump.
2638 Tabs are converted to clumps of spaces.
2639 Nonprintable characters may be converted to clumps of escape
2640 sequences or control prefixes.
2642 Note: the width of a clump is not necessarily equal to the number of
2643 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2644 number of characters is 1.) */
2647 char_to_clump (char c
)
2649 unsigned char uc
= c
;
2650 char *s
= clump_buff
;
2655 int chars_per_c
= 8;
2657 if (c
== input_tab_char
)
2658 chars_per_c
= chars_per_input_tab
;
2660 if (c
== input_tab_char
|| c
== '\t')
2662 width
= TAB_WIDTH (chars_per_c
, input_position
);
2666 for (i
= width
; i
; --i
)
2677 else if (! isprint (uc
))
2679 if (use_esc_sequence
)
2684 sprintf (esc_buff
, "%03o", uc
);
2685 for (i
= 0; i
<= 2; ++i
)
2688 else if (use_cntrl_prefix
)
2702 sprintf (esc_buff
, "%03o", uc
);
2703 for (i
= 0; i
<= 2; ++i
)
2727 /* Too many backspaces must put us in position 0 -- never negative. */
2728 if (width
< 0 && input_position
== 0)
2733 else if (width
< 0 && input_position
<= -width
)
2736 input_position
+= width
;
2741 /* We've just printed some files and need to clean up things before
2742 looking for more options and printing the next batch of files.
2744 Free everything we've xmalloc'ed, except `header'. */
2751 free (column_vector
);
2757 /* Complain, print a usage message, and die. */
2762 if (status
!= EXIT_SUCCESS
)
2763 fprintf (stderr
, _("Try `%s --help' for more information.\n"),
2768 Usage: %s [OPTION]... [FILE]...\n\
2773 Paginate or columnate FILE(s) for printing.\n\
2777 Mandatory arguments to long options are mandatory for short options too.\n\
2780 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2781 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2782 -COLUMN, --columns=COLUMN\n\
2783 output COLUMN columns and print columns down,\n\
2784 unless -a is used. Balance number of lines in the\n\
2785 columns on each page.\n\
2788 -a, --across print columns across rather than down, used together\n\
2790 -c, --show-control-chars\n\
2791 use hat notation (^G) and octal backslash notation\n\
2792 -d, --double-space\n\
2793 double space the output\n\
2796 -D, --date-format=FORMAT\n\
2797 use FORMAT for the header date\n\
2798 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2799 expand input CHARs (TABs) to tab WIDTH (8)\n\
2800 -F, -f, --form-feed\n\
2801 use form feeds instead of newlines to separate pages\n\
2802 (by a 3-line page header with -F or a 5-line header\n\
2803 and trailer without -F)\n\
2806 -h, --header=HEADER\n\
2807 use a centered HEADER instead of filename in page header,\n\
2808 -h \"\" prints a blank line, don't use -h\"\"\n\
2809 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2810 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2811 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2812 alignment, --sep-string[=STRING] sets separators\n\
2815 -l, --length=PAGE_LENGTH\n\
2816 set the page length to PAGE_LENGTH (66) lines\n\
2817 (default number of lines of text 56, and with -F 63)\n\
2818 -m, --merge print all files in parallel, one in each column,\n\
2819 truncate lines, but join lines of full length with -J\n\
2822 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2823 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2824 default counting starts with 1st line of input file\n\
2825 -N, --first-line-number=NUMBER\n\
2826 start counting with NUMBER at 1st line of first\n\
2827 page printed (see +FIRST_PAGE)\n\
2830 -o, --indent=MARGIN\n\
2831 offset each line with MARGIN (zero) spaces, do not\n\
2832 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2833 -r, --no-file-warnings\n\
2834 omit warning when a file cannot be opened\n\
2837 -s[CHAR],--separator[=CHAR]\n\
2838 separate columns by a single character, default for CHAR\n\
2839 is the <TAB> character without -w and \'no char\' with -w\n\
2840 -s[CHAR] turns off line truncation of all 3 column\n\
2841 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2844 -SSTRING, --sep-string[=STRING]\n\
2845 separate columns by STRING,\n\
2846 without -S: Default separator <TAB> with -J and <space>\n\
2847 otherwise (same as -S\" \"), no effect on column options\n\
2848 -t, --omit-header omit page headers and trailers\n\
2851 -T, --omit-pagination\n\
2852 omit page headers and trailers, eliminate any pagination\n\
2853 by form feeds set in input files\n\
2854 -v, --show-nonprinting\n\
2855 use octal backslash notation\n\
2856 -w, --width=PAGE_WIDTH\n\
2857 set page width to PAGE_WIDTH (72) characters for\n\
2858 multiple text-column output only, -s[char] turns off (72)\n\
2861 -W, --page-width=PAGE_WIDTH\n\
2862 set page width to PAGE_WIDTH (72) characters always,\n\
2863 truncate lines, except -J option is set, no interference\n\
2866 fputs (HELP_OPTION_DESCRIPTION
, stdout
);
2867 fputs (VERSION_OPTION_DESCRIPTION
, stdout
);
2870 -t is implied if PAGE_LENGTH <= 10. With no FILE, or when\n\
2871 FILE is -, read standard input.\n\
2873 emit_bug_reporting_address ();