build: support fully excluding stdbuf from the build
[coreutils/ericb.git] / src / pr.c
blobf942151a78f3b479d20e0c89c77684fae06c7ccc
1 /* pr -- convert text files for printing.
2 Copyright (C) 1988, 1991, 1995-2010 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* By Pete TerMaat, with considerable refinement by Roland Huebner. */
19 /* Things to watch: Sys V screws up on ...
20 pr -n -3 -s: /usr/dict/words
21 pr -m -o10 -n /usr/dict/words{,,,}
22 pr -6 -a -n -o5 /usr/dict/words
24 Ideas:
26 Keep a things_to_do list of functions to call when we know we have
27 something to print. Cleaner than current series of checks.
29 Improve the printing of control prefixes.
31 Expand the file name in the centered header line to a full file name.
34 Concept:
36 If the input_tab_char differs from the default value TAB
37 (`-e[CHAR[...]]' is used), any input text tab is expanded to the
38 default width of 8 spaces (compare char_to_clump). - Same as SunOS
39 does.
41 The treatment of the number_separator (compare add_line_number):
42 The default value TAB of the number_separator (`-n[SEP[...]]') doesn't
43 be thought to be an input character. An optional `-e'-input has no
44 effect.
45 - With single column output
46 only one POSIX requirement has to be met:
47 The default n-separator should be a TAB. The consequence is a
48 different width between the number and the text if the output position
49 of the separator changes, i.e. it depends upon the left margin used.
50 That's not nice but easy-to-use together with the defaults of other
51 utilities, e.g. sort or cut. - Same as SunOS does.
52 - With multicolumn output
53 two conflicting POSIX requirements exist:
54 First `default n-separator is TAB', second `output text columns shall
55 be of equal width'. Moreover POSIX specifies the number+separator a
56 part of the column, together with `-COLUMN' and `-a -COLUMN'.
57 (With -m output the number shall occupy each line only once. Exactly
58 the same situation as single column output exists.)
59 GNU pr gives priority to the 2nd requirement and observes POSIX
60 column definition. The n-separator TAB is expanded to the same number
61 of spaces in each column using the default value 8. Tabification is
62 only performed if it is compatible with the output position.
63 Consequence: The output text columns are of equal width. The layout
64 of a page does not change if the left margin varies. - Looks better
65 than the SunOS approach.
66 SunOS pr gives priority to the 1st requirement. n-separator TAB
67 width varies with each column. Only the width of text part of the
68 column is fixed.
69 Consequence: The output text columns don't have equal width. The
70 widths and the layout of the whole page varies with the left margin.
71 An overflow of the line length (without margin) over the input value
72 PAGE_WIDTH may occur.
74 The interference of the POSIX-compliant small letter options -w and -s:
75 (`interference' means `setting a _separator_ with -s switches off the
76 column structure and the default - not generally - page_width,
77 acts on -w option')
78 options: text form / separator: equivalent new options:
79 -w l -s[x]
80 --------------------------------------------------------------------
81 1. -- -- columns / space --
82 trunc. to page_width = 72
83 2. -- -s[:] full lines / TAB[:] -J --sep-string[="<TAB>"|:]
84 no truncation
85 3. -w l -- columns / space -W l
86 trunc. to page_width = l
87 4. -w l -s[:] columns / no sep.[:] -W l --sep-string[=:]
88 trunc. to page_width = l
89 --------------------------------------------------------------------
92 Options:
94 Including version 1.22i:
95 Some SMALL LETTER options have been redefined with the object of a
96 better POSIX compliance. The output of some further cases has been
97 adapted to other UNIXes. A violation of downward compatibility has to
98 be accepted.
99 Some NEW CAPITAL LETTER options ( -J, -S, -W) has been introduced to
100 turn off unexpected interferences of small letter options (-s and -w
101 together with the three column options).
102 -N option and the second argument LAST_PAGE of +FIRST_PAGE offer more
103 flexibility; The detailed handling of form feeds set in the input
104 files requires -T option.
106 Capital letter options dominate small letter ones.
108 Some of the option-arguments cannot be specified as separate arguments
109 from the preceding option letter (already stated in POSIX specification).
111 Form feeds in the input cause page breaks in the output. Multiple
112 form feeds produce empty pages.
114 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]
115 begin [stop] printing with page FIRST_[LAST_]PAGE
117 -COLUMN, --columns=COLUMN
118 Produce output that is COLUMN columns wide and
119 print columns down, unless -a is used. Balance number of
120 lines in the columns on each page.
122 -a, --across Print columns across rather than down, used
123 together with -COLUMN. The input
126 three
127 four
128 will be printed with `-a -3' as
129 one two three
130 four
132 -b Balance columns on the last page.
133 -b is no longer an independent option. It's always used
134 together with -COLUMN (unless -a is used) to get a
135 consistent formulation with "FF set by hand" in input
136 files. Each formfeed found terminates the number of lines
137 to be read with the actual page. The situation for
138 printing columns down is equivalent to that on the last
139 page. So we need a balancing.
141 Keeping -b as an underground option guarantees some
142 downward compatibility. Utilities using pr with -b
143 (a most frequently used form) still work as usual.
145 -c, --show-control-chars
146 Print unprintable characters as control prefixes.
147 Control-g is printed as ^G (use hat notation) and
148 octal backslash notation.
150 -d, --double-space Double space the output.
152 -D FORMAT, --date-format=FORMAT Use FORMAT for the header date.
154 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]
155 Expand tabs to spaces on input. Optional argument CHAR
156 is the input TAB character. (Default is TAB). Optional
157 argument WIDTH is the input TAB character's width.
158 (Default is 8.)
160 -F, -f, --form-feed Use formfeeds instead of newlines to separate
161 pages. A three line HEADER is used, no TRAILER with -F,
162 without -F both HEADER and TRAILER are made of five lines.
164 -h HEADER, --header=HEADER
165 Replace the filename in the header with the string HEADER.
166 A centered header is used.
168 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]
169 Replace spaces with tabs on output. Optional argument
170 CHAR is the output TAB character. (Default is TAB).
171 Optional argument WIDTH is the output TAB character's
172 width. (Default is 8)
174 -J, --join-lines Merge lines of full length, turns off -W/-w
175 line truncation, no column alignment, --sep-string[=STRING]
176 sets separators, works with all column options
177 (-COLUMN | -a -COLUMN | -m).
178 -J has been introduced (together with -W and --sep-string) to
179 disentangle the old (POSIX compliant) options -w, -s
180 along with the 3 column options.
182 -l PAGE_LENGTH, --length=PAGE_LENGTH
183 Set the page length to PAGE_LENGTH lines. Default is 66,
184 including 5 lines of HEADER and 5 lines of TRAILER
185 without -F, but only 3 lines of HEADER and no TRAILER
186 with -F (i.e the number of text lines defaults to 56 or
187 63 respectively).
189 -m, --merge Print files in parallel; pad_across_to align
190 columns; truncate lines and print separator strings;
191 Do it also with empty columns to get a continuous line
192 numbering and column marking by separators throughout
193 the whole merged file.
195 Empty pages in some input files produce empty columns
196 [marked by separators] in the merged pages. Completely
197 empty merged pages show no column separators at all.
199 The layout of a merged page is ruled by the largest form
200 feed distance of the single pages at that page. Shorter
201 columns will be filled up with empty lines.
203 Together with -J option join lines of full length and
204 set separators when -S option is used.
206 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]
207 Provide DIGITS digit line numbering (default for DIGITS
208 is 5). With multicolumn output the number occupies the
209 first DIGITS column positions of each text column or only
210 each line of -m output.
211 With single column output the number precedes each line
212 just as -m output.
213 Optional argument SEP is the character appended to the
214 line number to separate it from the text followed.
215 The default separator is a TAB. In a strict sense a TAB
216 is always printed with single column output only. The
217 TAB-width varies with the TAB-position, e.g. with the
218 left margin specified by -o option.
219 With multicolumn output priority is given to `equal width
220 of output columns' (a POSIX specification). The TAB-width
221 is fixed to the value of the 1st column and does not
222 change with different values of left margin. That means a
223 fixed number of spaces is always printed in the place of
224 a TAB. The tabification depends upon the output
225 position.
227 Default counting of the line numbers starts with 1st
228 line of the input file (not the 1st line printed,
229 compare the --page option and -N option).
231 -N NUMBER, --first-line-number=NUMBER
232 Start line counting with the number NUMBER at the 1st
233 line of first page printed (mostly not the 1st line of
234 the input file).
236 -o MARGIN, --indent=MARGIN
237 Offset each line with a margin MARGIN spaces wide.
238 Total page width is the size of the margin plus the
239 PAGE_WIDTH set with -W/-w option.
241 -r, --no-file-warnings
242 Omit warning when a file cannot be opened.
244 -s[CHAR], --separator[=CHAR]
245 Separate columns by a single character CHAR, default for
246 CHAR is the TAB character without -w and 'no char' with -w.
247 Without `-s' default separator `space' is set.
248 -s[CHAR] turns off line truncation of all 3 column options
249 (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX
250 compliant formulation. The source code translates -s into
251 the new options -S and -J, also -W if required.
253 -S STRING, --sep-string[=STRING]
254 Separate columns by any string STRING. The -S option
255 doesn't react upon the -W/-w option (unlike -s option
256 does). It defines a separator nothing else.
257 Without -S: Default separator TAB is used with -J and
258 `space' otherwise (same as -S" ").
259 With -S "": No separator is used.
260 Quotes should be used with blanks and some shell active
261 characters.
262 -S is problematic because in its obsolete form you
263 cannot use -S "STRING", but in its standard form you
264 must use -S "STRING" if STRING is empty. Use
265 --sep-string to avoid the ambiguity.
267 -t, --omit-header Do not print headers or footers but retain form
268 feeds set in the input files.
270 -T, --omit-pagination
271 Do not print headers or footers, eliminate any pagination
272 by form feeds set in the input files.
274 -v, --show-nonprinting
275 Print unprintable characters as escape sequences. Use
276 octal backslash notation. Control-G becomes \007.
278 -w PAGE_WIDTH, --width=PAGE_WIDTH
279 Set page width to PAGE_WIDTH characters for multiple
280 text-column output only (default for PAGE_WIDTH is 72).
281 -s[CHAR] turns off the default page width and any line
282 truncation. Lines of full length will be merged,
283 regardless of the column options set. A POSIX compliant
284 formulation.
286 -W PAGE_WIDTH, --page-width=PAGE_WIDTH
287 Set the page width to PAGE_WIDTH characters. That's valid
288 with and without a column option. Text lines will be
289 truncated, unless -J is used. Together with one of the
290 column options (-COLUMN| -a -COLUMN| -m) column alignment
291 is always used.
292 Default is 72 characters.
293 Without -W PAGE_WIDTH
294 - but with one of the column options default truncation of
295 72 characters is used (to keep downward compatibility
296 and to simplify most frequently met column tasks).
297 Column alignment and column separators are used.
298 - and without any of the column options NO line truncation
299 is used (to keep downward compatibility and to meet most
300 frequent tasks). That's equivalent to -W 72 -J .
302 With/without -W PAGE_WIDTH the header line is always
303 truncated to avoid line overflow.
305 (In pr versions newer than 1.14 -S option does no longer
306 affect -W option.)
311 #include <config.h>
313 #include <getopt.h>
314 #include <sys/types.h>
315 #include "system.h"
316 #include "error.h"
317 #include "hard-locale.h"
318 #include "mbswidth.h"
319 #include "quote.h"
320 #include "stat-time.h"
321 #include "stdio--.h"
322 #include "strftime.h"
323 #include "xstrtol.h"
325 /* The official name of this program (e.g., no `g' prefix). */
326 #define PROGRAM_NAME "pr"
328 #define AUTHORS \
329 proper_name ("Pete TerMaat"), \
330 proper_name ("Roland Huebner")
332 /* Used with start_position in the struct COLUMN described below.
333 If start_position == ANYWHERE, we aren't truncating columns and
334 can begin printing a column anywhere. Otherwise we must pad to
335 the horizontal position start_position. */
336 #define ANYWHERE 0
338 /* Each column has one of these structures allocated for it.
339 If we're only dealing with one file, fp is the same for all
340 columns.
342 The general strategy is to spend time setting up these column
343 structures (storing columns if necessary), after which printing
344 is a matter of flitting from column to column and calling
345 print_func.
347 Parallel files, single files printing across in multiple
348 columns, and single files printing down in multiple columns all
349 fit the same printing loop.
351 print_func Function used to print lines in this column.
352 If we're storing this column it will be
353 print_stored(), Otherwise it will be read_line().
355 char_func Function used to process characters in this column.
356 If we're storing this column it will be store_char(),
357 otherwise it will be print_char().
359 current_line Index of the current entry in line_vector, which
360 contains the index of the first character of the
361 current line in buff[].
363 lines_stored Number of lines in this column which are stored in
364 buff.
366 lines_to_print If we're storing this column, lines_to_print is
367 the number of stored_lines which remain to be
368 printed. Otherwise it is the number of lines
369 we can print without exceeding lines_per_body.
371 start_position The horizontal position we want to be in before we
372 print the first character in this column.
374 numbered True means precede this column with a line number. */
376 /* FIXME: There are many unchecked integer overflows in this file,
377 that will cause this command to misbehave given large inputs or
378 options. Many of the "int" values below should be "size_t" or
379 something else like that. */
381 struct COLUMN;
382 struct COLUMN
384 FILE *fp; /* Input stream for this column. */
385 char const *name; /* File name. */
386 enum
388 OPEN,
389 FF_FOUND, /* used with -b option, set with \f, changed
390 to ON_HOLD after print_header */
391 ON_HOLD, /* Hit a form feed. */
392 CLOSED
394 status; /* Status of the file pointer. */
396 /* Func to print lines in this col. */
397 bool (*print_func) (struct COLUMN *);
399 /* Func to print/store chars in this col. */
400 void (*char_func) (char);
402 int current_line; /* Index of current place in line_vector. */
403 int lines_stored; /* Number of lines stored in buff. */
404 int lines_to_print; /* No. lines stored or space left on page. */
405 int start_position; /* Horizontal position of first char. */
406 bool numbered;
407 bool full_page_printed; /* True means printed without a FF found. */
409 /* p->full_page_printed controls a special case of "FF set by hand":
410 True means a full page has been printed without FF found. To avoid an
411 additional empty page we have to ignore a FF immediately following in
412 the next line. */
415 typedef struct COLUMN COLUMN;
417 static int char_to_clump (char c);
418 static bool read_line (COLUMN *p);
419 static bool print_page (void);
420 static bool print_stored (COLUMN *p);
421 static bool open_file (char *name, COLUMN *p);
422 static bool skip_to_page (uintmax_t page);
423 static void print_header (void);
424 static void pad_across_to (int position);
425 static void add_line_number (COLUMN *p);
426 static void getoptarg (char *arg, char switch_char, char *character,
427 int *number);
428 void usage (int status);
429 static void print_files (int number_of_files, char **av);
430 static void init_parameters (int number_of_files);
431 static void init_header (char const *filename, int desc);
432 static bool init_fps (int number_of_files, char **av);
433 static void init_funcs (void);
434 static void init_store_cols (void);
435 static void store_columns (void);
436 static void balance (int total_stored);
437 static void store_char (char c);
438 static void pad_down (int lines);
439 static void read_rest_of_line (COLUMN *p);
440 static void skip_read (COLUMN *p, int column_number);
441 static void print_char (char c);
442 static void cleanup (void);
443 static void print_sep_string (void);
444 static void separator_string (const char *optarg_S);
446 /* All of the columns to print. */
447 static COLUMN *column_vector;
449 /* When printing a single file in multiple downward columns,
450 we store the leftmost columns contiguously in buff.
451 To print a line from buff, get the index of the first character
452 from line_vector[i], and print up to line_vector[i + 1]. */
453 static char *buff;
455 /* Index of the position in buff where the next character
456 will be stored. */
457 static unsigned int buff_current;
459 /* The number of characters in buff.
460 Used for allocation of buff and to detect overflow of buff. */
461 static size_t buff_allocated;
463 /* Array of indices into buff.
464 Each entry is an index of the first character of a line.
465 This is used when storing lines to facilitate shuffling when
466 we do column balancing on the last page. */
467 static int *line_vector;
469 /* Array of horizonal positions.
470 For each line in line_vector, end_vector[line] is the horizontal
471 position we are in after printing that line. We keep track of this
472 so that we know how much we need to pad to prepare for the next
473 column. */
474 static int *end_vector;
476 /* (-m) True means we're printing multiple files in parallel. */
477 static bool parallel_files = false;
479 /* (-m) True means a line starts with some empty columns (some files
480 already CLOSED or ON_HOLD) which we have to align. */
481 static bool align_empty_cols;
483 /* (-m) True means we have not yet found any printable column in a line.
484 align_empty_cols = true has to be maintained. */
485 static bool empty_line;
487 /* (-m) False means printable column output precedes a form feed found.
488 Column alignment is done only once. No additional action with that form
489 feed.
490 True means we found only a form feed in a column. Maybe we have to do
491 some column alignment with that form feed. */
492 static bool FF_only;
494 /* (-[0-9]+) True means we're given an option explicitly specifying
495 number of columns. Used to detect when this option is used with -m
496 and when translating old options to new/long options. */
497 static bool explicit_columns = false;
499 /* (-t|-T) False means we aren't printing headers and footers. */
500 static bool extremities = true;
502 /* (-t) True means we retain all FF set by hand in input files.
503 False is set with -T option. */
504 static bool keep_FF = false;
505 static bool print_a_FF = false;
507 /* True means we need to print a header as soon as we know we've got input
508 to print after it. */
509 static bool print_a_header;
511 /* (-f) True means use formfeeds instead of newlines to separate pages. */
512 static bool use_form_feed = false;
514 /* True means we have read the standard input. */
515 static bool have_read_stdin = false;
517 /* True means the -a flag has been given. */
518 static bool print_across_flag = false;
520 /* True means we're printing one file in multiple (>1) downward columns. */
521 static bool storing_columns = true;
523 /* (-b) True means balance columns on the last page as Sys V does. */
524 /* That's no longer an independent option. With storing_columns = true
525 balance_columns = true is used too (s. function init_parameters).
526 We get a consistent formulation with "FF set by hand" in input files. */
527 static bool balance_columns = false;
529 /* (-l) Number of lines on a page, including header and footer lines. */
530 static int lines_per_page = 66;
532 /* Number of lines in the header and footer can be reset to 0 using
533 the -t flag. */
534 enum { lines_per_header = 5 };
535 static int lines_per_body;
536 enum { lines_per_footer = 5 };
538 /* (-w|-W) Width in characters of the page. Does not include the width of
539 the margin. */
540 static int chars_per_line = 72;
542 /* (-w|W) True means we truncate lines longer than chars_per_column. */
543 static bool truncate_lines = false;
545 /* (-J) True means we join lines without any line truncation. -J
546 dominates -w option. */
547 static bool join_lines = false;
549 /* Number of characters in a column. Based on col_sep_length and
550 page width. */
551 static int chars_per_column;
553 /* (-e) True means convert tabs to spaces on input. */
554 static bool untabify_input = false;
556 /* (-e) The input tab character. */
557 static char input_tab_char = '\t';
559 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
560 where the leftmost column is 1. */
561 static int chars_per_input_tab = 8;
563 /* (-i) True means convert spaces to tabs on output. */
564 static bool tabify_output = false;
566 /* (-i) The output tab character. */
567 static char output_tab_char = '\t';
569 /* (-i) The width of the output tab. */
570 static int chars_per_output_tab = 8;
572 /* Keeps track of pending white space. When we hit a nonspace
573 character after some whitespace, we print whitespace, tabbing
574 if necessary to get to output_position + spaces_not_printed. */
575 static int spaces_not_printed;
577 /* (-o) Number of spaces in the left margin (tabs used when possible). */
578 static int chars_per_margin = 0;
580 /* Position where the next character will fall.
581 Leftmost position is 0 + chars_per_margin.
582 Rightmost position is chars_per_margin + chars_per_line - 1.
583 This is important for converting spaces to tabs on output. */
584 static int output_position;
586 /* Horizontal position relative to the current file.
587 (output_position depends on where we are on the page;
588 input_position depends on where we are in the file.)
589 Important for converting tabs to spaces on input. */
590 static int input_position;
592 /* True if there were any failed opens so we can exit with nonzero
593 status. */
594 static bool failed_opens = false;
596 /* The number of spaces taken up if we print a tab character with width
597 c_ from position h_. */
598 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
600 /* The horizontal position we'll be at after printing a tab character
601 of width c_ from the position h_. */
602 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
604 /* (-NNN) Number of columns of text to print. */
605 static int columns = 1;
607 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
608 first_page_number = 0 will be used to check input only. */
609 static uintmax_t first_page_number = 0;
610 static uintmax_t last_page_number = UINTMAX_MAX;
612 /* Number of files open (not closed, not on hold). */
613 static int files_ready_to_read = 0;
615 /* Current page number. Displayed in header. */
616 static uintmax_t page_number;
618 /* Current line number. Displayed when -n flag is specified.
620 When printing files in parallel (-m flag), line numbering is as follows:
621 1 foo goo moo
622 2 hoo too zoo
624 When printing files across (-a flag), ...
625 1 foo 2 moo 3 goo
626 4 hoo 5 too 6 zoo
628 Otherwise, line numbering is as follows:
629 1 foo 3 goo 5 too
630 2 moo 4 hoo 6 zoo */
631 static int line_number;
633 /* With line_number overflow, we use power_10 to cut off the higher-order
634 digits of the line_number */
635 static int power_10;
637 /* (-n) True means lines should be preceded by numbers. */
638 static bool numbered_lines = false;
640 /* (-n) Character which follows each line number. */
641 static char number_separator = '\t';
643 /* (-n) line counting starts with 1st line of input file (not with 1st
644 line of 1st page printed). */
645 static int line_count = 1;
647 /* (-n) True means counting of skipped lines starts with 1st line of
648 input file. False means -N option is used in addition, counting of
649 skipped lines not required. */
650 static bool skip_count = true;
652 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
653 first page printed, usually not 1st page of input file. */
654 static int start_line_num = 1;
656 /* (-n) Width in characters of a line number. */
657 static int chars_per_number = 5;
659 /* Used when widening the first column to accommodate numbers -- only
660 needed when printing files in parallel. Includes width of both the
661 number and the number_separator. */
662 static int number_width;
664 /* Buffer sprintf uses to format a line number. */
665 static char *number_buff;
667 /* (-v) True means unprintable characters are printed as escape sequences.
668 control-g becomes \007. */
669 static bool use_esc_sequence = false;
671 /* (-c) True means unprintable characters are printed as control prefixes.
672 control-g becomes ^G. */
673 static bool use_cntrl_prefix = false;
675 /* (-d) True means output is double spaced. */
676 static bool double_space = false;
678 /* Number of files opened initially in init_files. Should be 1
679 unless we're printing multiple files in parallel. */
680 static int total_files = 0;
682 /* (-r) True means don't complain if we can't open a file. */
683 static bool ignore_failed_opens = false;
685 /* (-S) True means we separate columns with a specified string.
686 -S option does not affect line truncation nor column alignment. */
687 static bool use_col_separator = false;
689 /* String used to separate columns if the -S option has been specified.
690 Default without -S but together with one of the column options
691 -a|COLUMN|-m is a `space' and with the -J option a `tab'. */
692 static char *col_sep_string = (char *) "";
693 static int col_sep_length = 0;
694 static char *column_separator = (char *) " ";
695 static char *line_separator = (char *) "\t";
697 /* Number of separator characters waiting to be printed as soon as we
698 know that we have any input remaining to be printed. */
699 static int separators_not_printed;
701 /* Position we need to pad to, as soon as we know that we have input
702 remaining to be printed. */
703 static int padding_not_printed;
705 /* True means we should pad the end of the page. Remains false until we
706 know we have a page to print. */
707 static bool pad_vertically;
709 /* (-h) String of characters used in place of the filename in the header. */
710 static char *custom_header;
712 /* (-D) Date format for the header. */
713 static char const *date_format;
715 /* Date and file name for the header. */
716 static char *date_text;
717 static char const *file_text;
719 /* Output columns available, not counting the date and file name. */
720 static int header_width_available;
722 static char *clump_buff;
724 /* True means we read the line no. lines_per_body in skip_read
725 called by skip_to_page. That variable controls the coincidence of a
726 "FF set by hand" and "full_page_printed", see above the definition of
727 structure COLUMN. */
728 static bool last_line = false;
730 /* For long options that have no equivalent short option, use a
731 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
732 enum
734 COLUMNS_OPTION = CHAR_MAX + 1,
735 PAGES_OPTION
738 static char const short_options[] =
739 "-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
741 static struct option const long_options[] =
743 {"pages", required_argument, NULL, PAGES_OPTION},
744 {"columns", required_argument, NULL, COLUMNS_OPTION},
745 {"across", no_argument, NULL, 'a'},
746 {"show-control-chars", no_argument, NULL, 'c'},
747 {"double-space", no_argument, NULL, 'd'},
748 {"date-format", required_argument, NULL, 'D'},
749 {"expand-tabs", optional_argument, NULL, 'e'},
750 {"form-feed", no_argument, NULL, 'f'},
751 {"header", required_argument, NULL, 'h'},
752 {"output-tabs", optional_argument, NULL, 'i'},
753 {"join-lines", no_argument, NULL, 'J'},
754 {"length", required_argument, NULL, 'l'},
755 {"merge", no_argument, NULL, 'm'},
756 {"number-lines", optional_argument, NULL, 'n'},
757 {"first-line-number", required_argument, NULL, 'N'},
758 {"indent", required_argument, NULL, 'o'},
759 {"no-file-warnings", no_argument, NULL, 'r'},
760 {"separator", optional_argument, NULL, 's'},
761 {"sep-string", optional_argument, NULL, 'S'},
762 {"omit-header", no_argument, NULL, 't'},
763 {"omit-pagination", no_argument, NULL, 'T'},
764 {"show-nonprinting", no_argument, NULL, 'v'},
765 {"width", required_argument, NULL, 'w'},
766 {"page-width", required_argument, NULL, 'W'},
767 {GETOPT_HELP_OPTION_DECL},
768 {GETOPT_VERSION_OPTION_DECL},
769 {NULL, 0, NULL, 0}
772 /* Return the number of columns that have either an open file or
773 stored lines. */
775 static int
776 cols_ready_to_print (void)
778 COLUMN *q;
779 int i;
780 int n;
782 n = 0;
783 for (q = column_vector, i = 0; i < columns; ++q, ++i)
784 if (q->status == OPEN ||
785 q->status == FF_FOUND || /* With -b: To print a header only */
786 (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
787 ++n;
788 return n;
791 /* Estimate first_ / last_page_number
792 using option +FIRST_PAGE:LAST_PAGE */
794 static bool
795 first_last_page (int oi, char c, char const *pages)
797 char *p;
798 uintmax_t first;
799 uintmax_t last = UINTMAX_MAX;
800 strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
801 if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
802 xstrtol_fatal (err, oi, c, long_options, pages);
804 if (p == pages || !first)
805 return false;
807 if (*p == ':')
809 char const *p1 = p + 1;
810 err = xstrtoumax (p1, &p, 10, &last, "");
811 if (err != LONGINT_OK)
812 xstrtol_fatal (err, oi, c, long_options, pages);
813 if (p1 == p || last < first)
814 return false;
817 if (*p)
818 return false;
820 first_page_number = first;
821 last_page_number = last;
822 return true;
825 /* Parse column count string S, and if it's valid (1 or larger and
826 within range of the type of `columns') set the global variables
827 columns and explicit_columns and return true.
828 Otherwise, exit with a diagnostic. */
829 static void
830 parse_column_count (char const *s)
832 long int tmp_long;
833 if (xstrtol (s, NULL, 10, &tmp_long, "") != LONGINT_OK
834 || !(1 <= tmp_long && tmp_long <= INT_MAX))
835 error (EXIT_FAILURE, 0,
836 _("invalid number of columns: %s"), quote (s));
838 columns = tmp_long;
839 explicit_columns = true;
842 /* Estimate length of col_sep_string with option -S. */
844 static void
845 separator_string (const char *optarg_S)
847 col_sep_length = (int) strlen (optarg_S);
848 col_sep_string = xmalloc (col_sep_length + 1);
849 strcpy (col_sep_string, optarg_S);
853 main (int argc, char **argv)
855 int n_files;
856 bool old_options = false;
857 bool old_w = false;
858 bool old_s = false;
859 char **file_names;
861 /* Accumulate the digits of old-style options like -99. */
862 char *column_count_string = NULL;
863 size_t n_digits = 0;
864 size_t n_alloc = 0;
866 initialize_main (&argc, &argv);
867 set_program_name (argv[0]);
868 setlocale (LC_ALL, "");
869 bindtextdomain (PACKAGE, LOCALEDIR);
870 textdomain (PACKAGE);
872 atexit (close_stdout);
874 n_files = 0;
875 file_names = (argc > 1
876 ? xmalloc ((argc - 1) * sizeof (char *))
877 : NULL);
879 while (true)
881 int oi = -1;
882 int c = getopt_long (argc, argv, short_options, long_options, &oi);
883 if (c == -1)
884 break;
886 if (ISDIGIT (c))
888 /* Accumulate column-count digits specified via old-style options. */
889 if (n_digits + 1 >= n_alloc)
890 column_count_string
891 = X2REALLOC (column_count_string, &n_alloc);
892 column_count_string[n_digits++] = c;
893 column_count_string[n_digits] = '\0';
894 continue;
897 n_digits = 0;
899 switch (c)
901 case 1: /* Non-option argument. */
902 /* long option --page dominates old `+FIRST_PAGE ...'. */
903 if (! (first_page_number == 0
904 && *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
905 file_names[n_files++] = optarg;
906 break;
908 case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
909 { /* dominates old opt +... */
910 if (! optarg)
911 error (EXIT_FAILURE, 0,
912 _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
913 else if (! first_last_page (oi, 0, optarg))
914 error (EXIT_FAILURE, 0, _("invalid page range %s"),
915 quote (optarg));
916 break;
919 case COLUMNS_OPTION: /* --columns=COLUMN */
921 parse_column_count (optarg);
923 /* If there was a prior column count specified via the
924 short-named option syntax, e.g., -9, ensure that this
925 long-name-specified value overrides it. */
926 free (column_count_string);
927 column_count_string = NULL;
928 n_alloc = 0;
929 break;
932 case 'a':
933 print_across_flag = true;
934 storing_columns = false;
935 break;
936 case 'b':
937 balance_columns = true;
938 break;
939 case 'c':
940 use_cntrl_prefix = true;
941 break;
942 case 'd':
943 double_space = true;
944 break;
945 case 'D':
946 date_format = optarg;
947 break;
948 case 'e':
949 if (optarg)
950 getoptarg (optarg, 'e', &input_tab_char,
951 &chars_per_input_tab);
952 /* Could check tab width > 0. */
953 untabify_input = true;
954 break;
955 case 'f':
956 case 'F':
957 use_form_feed = true;
958 break;
959 case 'h':
960 custom_header = optarg;
961 break;
962 case 'i':
963 if (optarg)
964 getoptarg (optarg, 'i', &output_tab_char,
965 &chars_per_output_tab);
966 /* Could check tab width > 0. */
967 tabify_output = true;
968 break;
969 case 'J':
970 join_lines = true;
971 break;
972 case 'l':
974 long int tmp_long;
975 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
976 || tmp_long <= 0 || tmp_long > INT_MAX)
978 error (EXIT_FAILURE, 0,
979 _("`-l PAGE_LENGTH' invalid number of lines: %s"),
980 quote (optarg));
982 lines_per_page = tmp_long;
983 break;
985 case 'm':
986 parallel_files = true;
987 storing_columns = false;
988 break;
989 case 'n':
990 numbered_lines = true;
991 if (optarg)
992 getoptarg (optarg, 'n', &number_separator,
993 &chars_per_number);
994 break;
995 case 'N':
996 skip_count = false;
998 long int tmp_long;
999 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1000 || tmp_long > INT_MAX)
1002 error (EXIT_FAILURE, 0,
1003 _("`-N NUMBER' invalid starting line number: %s"),
1004 quote (optarg));
1006 start_line_num = tmp_long;
1007 break;
1009 case 'o':
1011 long int tmp_long;
1012 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1013 || tmp_long < 0 || tmp_long > INT_MAX)
1014 error (EXIT_FAILURE, 0,
1015 _("`-o MARGIN' invalid line offset: %s"), quote (optarg));
1016 chars_per_margin = tmp_long;
1017 break;
1019 case 'r':
1020 ignore_failed_opens = true;
1021 break;
1022 case 's':
1023 old_options = true;
1024 old_s = true;
1025 if (!use_col_separator && optarg)
1026 separator_string (optarg);
1027 break;
1028 case 'S':
1029 old_s = false;
1030 /* Reset an additional input of -s, -S dominates -s */
1031 col_sep_string = bad_cast ("");
1032 col_sep_length = 0;
1033 use_col_separator = true;
1034 if (optarg)
1035 separator_string (optarg);
1036 break;
1037 case 't':
1038 extremities = false;
1039 keep_FF = true;
1040 break;
1041 case 'T':
1042 extremities = false;
1043 keep_FF = false;
1044 break;
1045 case 'v':
1046 use_esc_sequence = true;
1047 break;
1048 case 'w':
1049 old_options = true;
1050 old_w = true;
1052 long int tmp_long;
1053 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1054 || tmp_long <= 0 || tmp_long > INT_MAX)
1055 error (EXIT_FAILURE, 0,
1056 _("`-w PAGE_WIDTH' invalid number of characters: %s"),
1057 quote (optarg));
1058 if (!truncate_lines)
1059 chars_per_line = tmp_long;
1060 break;
1062 case 'W':
1063 old_w = false; /* dominates -w */
1064 truncate_lines = true;
1066 long int tmp_long;
1067 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1068 || tmp_long <= 0 || tmp_long > INT_MAX)
1069 error (EXIT_FAILURE, 0,
1070 _("`-W PAGE_WIDTH' invalid number of characters: %s"),
1071 quote (optarg));
1072 chars_per_line = tmp_long;
1073 break;
1075 case_GETOPT_HELP_CHAR;
1076 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1077 default:
1078 usage (EXIT_FAILURE);
1079 break;
1083 if (column_count_string)
1085 parse_column_count (column_count_string);
1086 free (column_count_string);
1089 if (! date_format)
1090 date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME)
1091 ? "%b %e %H:%M %Y"
1092 : "%Y-%m-%d %H:%M");
1094 /* Now we can set a reasonable initial value: */
1095 if (first_page_number == 0)
1096 first_page_number = 1;
1098 if (parallel_files && explicit_columns)
1099 error (EXIT_FAILURE, 0,
1100 _("cannot specify number of columns when printing in parallel"));
1102 if (parallel_files && print_across_flag)
1103 error (EXIT_FAILURE, 0,
1104 _("cannot specify both printing across and printing in parallel"));
1106 /* Translate some old short options to new/long options.
1107 To meet downward compatibility with other UNIX pr utilities
1108 and some POSIX specifications. */
1110 if (old_options)
1112 if (old_w)
1114 if (parallel_files || explicit_columns)
1116 /* activate -W */
1117 truncate_lines = true;
1118 if (old_s)
1119 /* adapt HP-UX and SunOS: -s = no separator;
1120 activate -S */
1121 use_col_separator = true;
1123 else
1124 /* old -w sets width with columns only
1125 activate -J */
1126 join_lines = true;
1128 else if (!use_col_separator)
1130 /* No -S option read */
1131 if (old_s && (parallel_files || explicit_columns))
1133 if (!truncate_lines)
1135 /* old -s (without -w and -W) annuls column alignment,
1136 uses fields, activate -J */
1137 join_lines = true;
1138 if (col_sep_length > 0)
1139 /* activate -S */
1140 use_col_separator = true;
1142 else
1143 /* with -W */
1144 /* adapt HP-UX and SunOS: -s = no separator;
1145 activate -S */
1146 use_col_separator = true;
1151 for (; optind < argc; optind++)
1153 file_names[n_files++] = argv[optind];
1156 if (n_files == 0)
1158 /* No file arguments specified; read from standard input. */
1159 print_files (0, NULL);
1161 else
1163 if (parallel_files)
1164 print_files (n_files, file_names);
1165 else
1167 int i;
1168 for (i = 0; i < n_files; i++)
1169 print_files (1, &file_names[i]);
1173 cleanup ();
1175 if (have_read_stdin && fclose (stdin) == EOF)
1176 error (EXIT_FAILURE, errno, _("standard input"));
1177 if (failed_opens)
1178 exit (EXIT_FAILURE);
1179 exit (EXIT_SUCCESS);
1182 /* Parse options of the form -scNNN.
1184 Example: -nck, where 'n' is the option, c is the optional number
1185 separator, and k is the optional width of the field used when printing
1186 a number. */
1188 static void
1189 getoptarg (char *arg, char switch_char, char *character, int *number)
1191 if (!ISDIGIT (*arg))
1192 *character = *arg++;
1193 if (*arg)
1195 long int tmp_long;
1196 if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK
1197 || tmp_long <= 0 || tmp_long > INT_MAX)
1199 error (0, 0,
1200 _("`-%c' extra characters or invalid number in the argument: %s"),
1201 switch_char, quote (arg));
1202 usage (EXIT_FAILURE);
1204 *number = tmp_long;
1208 /* Set parameters related to formatting. */
1210 static void
1211 init_parameters (int number_of_files)
1213 int chars_used_by_number = 0;
1215 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1216 if (lines_per_body <= 0)
1218 extremities = false;
1219 keep_FF = true;
1221 if (extremities == false)
1222 lines_per_body = lines_per_page;
1224 if (double_space)
1225 lines_per_body = lines_per_body / 2;
1227 /* If input is stdin, cannot print parallel files. BSD dumps core
1228 on this. */
1229 if (number_of_files == 0)
1230 parallel_files = false;
1232 if (parallel_files)
1233 columns = number_of_files;
1235 /* One file, multi columns down: -b option is set to get a consistent
1236 formulation with "FF set by hand" in input files. */
1237 if (storing_columns)
1238 balance_columns = true;
1240 /* Tabification is assumed for multiple columns. */
1241 if (columns > 1)
1243 if (!use_col_separator)
1245 /* Use default separator */
1246 if (join_lines)
1247 col_sep_string = line_separator;
1248 else
1249 col_sep_string = column_separator;
1251 col_sep_length = 1;
1252 use_col_separator = true;
1254 /* It's rather pointless to define a TAB separator with column
1255 alignment */
1256 else if (!join_lines && *col_sep_string == '\t')
1257 col_sep_string = column_separator;
1259 truncate_lines = true;
1260 tabify_output = true;
1262 else
1263 storing_columns = false;
1265 /* -J dominates -w in any case */
1266 if (join_lines)
1267 truncate_lines = false;
1269 if (numbered_lines)
1271 int tmp_i;
1272 int chars_per_default_tab = 8;
1274 line_count = start_line_num;
1276 /* To allow input tab-expansion (-e sensitive) use:
1277 if (number_separator == input_tab_char)
1278 number_width = chars_per_number +
1279 TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1281 /* Estimate chars_per_text without any margin and keep it constant. */
1282 if (number_separator == '\t')
1283 number_width = chars_per_number +
1284 TAB_WIDTH (chars_per_default_tab, chars_per_number);
1285 else
1286 number_width = chars_per_number + 1;
1288 /* The number is part of the column width unless we are
1289 printing files in parallel. */
1290 if (parallel_files)
1291 chars_used_by_number = number_width;
1293 /* We use power_10 to cut off the higher-order digits of the
1294 line_number in function add_line_number */
1295 tmp_i = chars_per_number;
1296 for (power_10 = 1; tmp_i > 0; --tmp_i)
1297 power_10 = 10 * power_10;
1300 chars_per_column = (chars_per_line - chars_used_by_number -
1301 (columns - 1) * col_sep_length) / columns;
1303 if (chars_per_column < 1)
1304 error (EXIT_FAILURE, 0, _("page width too narrow"));
1306 if (numbered_lines)
1308 free (number_buff);
1309 number_buff = xmalloc (2 * chars_per_number);
1312 /* Pick the maximum between the tab width and the width of an
1313 escape sequence.
1314 The width of an escape sequence (4) isn't the lower limit any longer.
1315 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1316 to expand a tab which is not an input_tab-char. */
1317 free (clump_buff);
1318 clump_buff = xmalloc (MAX (8, chars_per_input_tab));
1321 /* Open the necessary files,
1322 maintaining a COLUMN structure for each column.
1324 With multiple files, each column p has a different p->fp.
1325 With single files, each column p has the same p->fp.
1326 Return false if (number_of_files > 0) and no files can be opened,
1327 true otherwise.
1329 With each column/file p, p->full_page_printed is initialized,
1330 see also open_file. */
1332 static bool
1333 init_fps (int number_of_files, char **av)
1335 int i, files_left;
1336 COLUMN *p;
1337 FILE *firstfp;
1338 char const *firstname;
1340 total_files = 0;
1342 free (column_vector);
1343 column_vector = xnmalloc (columns, sizeof (COLUMN));
1345 if (parallel_files)
1347 files_left = number_of_files;
1348 for (p = column_vector; files_left--; ++p, ++av)
1350 if (! open_file (*av, p))
1352 --p;
1353 --columns;
1356 if (columns == 0)
1357 return false;
1358 init_header ("", -1);
1360 else
1362 p = column_vector;
1363 if (number_of_files > 0)
1365 if (! open_file (*av, p))
1366 return false;
1367 init_header (*av, fileno (p->fp));
1368 p->lines_stored = 0;
1370 else
1372 p->name = _("standard input");
1373 p->fp = stdin;
1374 have_read_stdin = true;
1375 p->status = OPEN;
1376 p->full_page_printed = false;
1377 ++total_files;
1378 init_header ("", -1);
1379 p->lines_stored = 0;
1382 firstname = p->name;
1383 firstfp = p->fp;
1384 for (i = columns - 1, ++p; i; --i, ++p)
1386 p->name = firstname;
1387 p->fp = firstfp;
1388 p->status = OPEN;
1389 p->full_page_printed = false;
1390 p->lines_stored = 0;
1393 files_ready_to_read = total_files;
1394 return true;
1397 /* Determine print_func and char_func, the functions
1398 used by each column for printing and/or storing.
1400 Determine the horizontal position desired when we begin
1401 printing a column (p->start_position). */
1403 static void
1404 init_funcs (void)
1406 int i, h, h_next;
1407 COLUMN *p;
1409 h = chars_per_margin;
1411 if (!truncate_lines)
1412 h_next = ANYWHERE;
1413 else
1415 /* When numbering lines of parallel files, we enlarge the
1416 first column to accomodate the number. Looks better than
1417 the Sys V approach. */
1418 if (parallel_files && numbered_lines)
1419 h_next = h + chars_per_column + number_width;
1420 else
1421 h_next = h + chars_per_column;
1424 /* Enlarge p->start_position of first column to use the same form of
1425 padding_not_printed with all columns. */
1426 h = h + col_sep_length;
1428 /* This loop takes care of all but the rightmost column. */
1430 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1432 if (storing_columns) /* One file, multi columns down. */
1434 p->char_func = store_char;
1435 p->print_func = print_stored;
1437 else
1438 /* One file, multi columns across; or parallel files. */
1440 p->char_func = print_char;
1441 p->print_func = read_line;
1444 /* Number only the first column when printing files in
1445 parallel. */
1446 p->numbered = numbered_lines && (!parallel_files || i == 1);
1447 p->start_position = h;
1449 /* If we don't truncate lines, all start_positions are
1450 ANYWHERE, except the first column's start_position when
1451 using a margin. */
1453 if (!truncate_lines)
1455 h = ANYWHERE;
1456 h_next = ANYWHERE;
1458 else
1460 h = h_next + col_sep_length;
1461 h_next = h + chars_per_column;
1465 /* The rightmost column.
1467 Doesn't need to be stored unless we intend to balance
1468 columns on the last page. */
1469 if (storing_columns && balance_columns)
1471 p->char_func = store_char;
1472 p->print_func = print_stored;
1474 else
1476 p->char_func = print_char;
1477 p->print_func = read_line;
1480 p->numbered = numbered_lines && (!parallel_files || i == 1);
1481 p->start_position = h;
1484 /* Open a file. Return true if successful.
1486 With each file p, p->full_page_printed is initialized,
1487 see also init_fps. */
1489 static bool
1490 open_file (char *name, COLUMN *p)
1492 if (STREQ (name, "-"))
1494 p->name = _("standard input");
1495 p->fp = stdin;
1496 have_read_stdin = true;
1498 else
1500 p->name = name;
1501 p->fp = fopen (name, "r");
1503 if (p->fp == NULL)
1505 failed_opens = true;
1506 if (!ignore_failed_opens)
1507 error (0, errno, "%s", name);
1508 return false;
1510 p->status = OPEN;
1511 p->full_page_printed = false;
1512 ++total_files;
1513 return true;
1516 /* Close the file in P.
1518 If we aren't dealing with multiple files in parallel, we change
1519 the status of all columns in the column list to reflect the close. */
1521 static void
1522 close_file (COLUMN *p)
1524 COLUMN *q;
1525 int i;
1527 if (p->status == CLOSED)
1528 return;
1529 if (ferror (p->fp))
1530 error (EXIT_FAILURE, errno, "%s", p->name);
1531 if (fileno (p->fp) != STDIN_FILENO && fclose (p->fp) != 0)
1532 error (EXIT_FAILURE, errno, "%s", p->name);
1534 if (!parallel_files)
1536 for (q = column_vector, i = columns; i; ++q, --i)
1538 q->status = CLOSED;
1539 if (q->lines_stored == 0)
1541 q->lines_to_print = 0;
1545 else
1547 p->status = CLOSED;
1548 p->lines_to_print = 0;
1551 --files_ready_to_read;
1554 /* Put a file on hold until we start a new page,
1555 since we've hit a form feed.
1557 If we aren't dealing with parallel files, we must change the
1558 status of all columns in the column list. */
1560 static void
1561 hold_file (COLUMN *p)
1563 COLUMN *q;
1564 int i;
1566 if (!parallel_files)
1567 for (q = column_vector, i = columns; i; ++q, --i)
1569 if (storing_columns)
1570 q->status = FF_FOUND;
1571 else
1572 q->status = ON_HOLD;
1574 else
1575 p->status = ON_HOLD;
1577 p->lines_to_print = 0;
1578 --files_ready_to_read;
1581 /* Undo hold_file -- go through the column list and change any
1582 ON_HOLD columns to OPEN. Used at the end of each page. */
1584 static void
1585 reset_status (void)
1587 int i = columns;
1588 COLUMN *p;
1590 for (p = column_vector; i; --i, ++p)
1591 if (p->status == ON_HOLD)
1593 p->status = OPEN;
1594 files_ready_to_read++;
1597 if (storing_columns)
1599 if (column_vector->status == CLOSED)
1600 /* We use the info to output an error message in skip_to_page. */
1601 files_ready_to_read = 0;
1602 else
1603 files_ready_to_read = 1;
1607 /* Print a single file, or multiple files in parallel.
1609 Set up the list of columns, opening the necessary files.
1610 Allocate space for storing columns, if necessary.
1611 Skip to first_page_number, if user has asked to skip leading pages.
1612 Determine which functions are appropriate to store/print lines
1613 in each column.
1614 Print the file(s). */
1616 static void
1617 print_files (int number_of_files, char **av)
1619 init_parameters (number_of_files);
1620 if (! init_fps (number_of_files, av))
1621 return;
1622 if (storing_columns)
1623 init_store_cols ();
1625 if (first_page_number > 1)
1627 if (!skip_to_page (first_page_number))
1628 return;
1629 else
1630 page_number = first_page_number;
1632 else
1633 page_number = 1;
1635 init_funcs ();
1637 line_number = line_count;
1638 while (print_page ())
1642 /* Initialize header information.
1643 If DESC is non-negative, it is a file descriptor open to
1644 FILENAME for reading. */
1646 static void
1647 init_header (char const *filename, int desc)
1649 char *buf = NULL;
1650 struct stat st;
1651 struct timespec t;
1652 int ns;
1653 struct tm *tm;
1655 /* If parallel files or standard input, use current date. */
1656 if (STREQ (filename, "-"))
1657 desc = -1;
1658 if (0 <= desc && fstat (desc, &st) == 0)
1659 t = get_stat_mtime (&st);
1660 else
1662 static struct timespec timespec;
1663 if (! timespec.tv_sec)
1664 gettime (&timespec);
1665 t = timespec;
1668 ns = t.tv_nsec;
1669 tm = localtime (&t.tv_sec);
1670 if (tm == NULL)
1672 buf = xmalloc (INT_BUFSIZE_BOUND (long int)
1673 + MAX (10, INT_BUFSIZE_BOUND (int)));
1674 sprintf (buf, "%ld.%09d", (long int) t.tv_sec, ns);
1676 else
1678 size_t bufsize = nstrftime (NULL, SIZE_MAX, date_format, tm, 0, ns) + 1;
1679 buf = xmalloc (bufsize);
1680 nstrftime (buf, bufsize, date_format, tm, 0, ns);
1683 free (date_text);
1684 date_text = buf;
1685 file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1686 header_width_available = (chars_per_line
1687 - mbswidth (date_text, 0)
1688 - mbswidth (file_text, 0));
1691 /* Set things up for printing a page
1693 Scan through the columns ...
1694 Determine which are ready to print
1695 (i.e., which have lines stored or open files)
1696 Set p->lines_to_print appropriately
1697 (to p->lines_stored if we're storing, or lines_per_body
1698 if we're reading straight from the file)
1699 Keep track of this total so we know when to stop printing */
1701 static void
1702 init_page (void)
1704 int j;
1705 COLUMN *p;
1707 if (storing_columns)
1709 store_columns ();
1710 for (j = columns - 1, p = column_vector; j; --j, ++p)
1712 p->lines_to_print = p->lines_stored;
1715 /* Last column. */
1716 if (balance_columns)
1718 p->lines_to_print = p->lines_stored;
1720 /* Since we're not balancing columns, we don't need to store
1721 the rightmost column. Read it straight from the file. */
1722 else
1724 if (p->status == OPEN)
1726 p->lines_to_print = lines_per_body;
1728 else
1729 p->lines_to_print = 0;
1732 else
1733 for (j = columns, p = column_vector; j; --j, ++p)
1734 if (p->status == OPEN)
1736 p->lines_to_print = lines_per_body;
1738 else
1739 p->lines_to_print = 0;
1742 /* Align empty columns and print separators.
1743 Empty columns will be formed by files with status ON_HOLD or CLOSED
1744 when printing multiple files in parallel. */
1746 static void
1747 align_column (COLUMN *p)
1749 padding_not_printed = p->start_position;
1750 if (padding_not_printed - col_sep_length > 0)
1752 pad_across_to (padding_not_printed - col_sep_length);
1753 padding_not_printed = ANYWHERE;
1756 if (use_col_separator)
1757 print_sep_string ();
1759 if (p->numbered)
1760 add_line_number (p);
1763 /* Print one page.
1765 As long as there are lines left on the page and columns ready to print,
1766 Scan across the column list
1767 if the column has stored lines or the file is open
1768 pad to the appropriate spot
1769 print the column
1770 pad the remainder of the page with \n or \f as requested
1771 reset the status of all files -- any files which where on hold because
1772 of formfeeds are now put back into the lineup. */
1774 static bool
1775 print_page (void)
1777 int j;
1778 int lines_left_on_page;
1779 COLUMN *p;
1781 /* Used as an accumulator (with | operator) of successive values of
1782 pad_vertically. The trick is to set pad_vertically
1783 to false before each run through the inner loop, then after that
1784 loop, it tells us whether a line was actually printed (whether a
1785 newline needs to be output -- or two for double spacing). But those
1786 values have to be accumulated (in pv) so we can invoke pad_down
1787 properly after the outer loop completes. */
1788 bool pv;
1790 init_page ();
1792 if (cols_ready_to_print () == 0)
1793 return false;
1795 if (extremities)
1796 print_a_header = true;
1798 /* Don't pad unless we know a page was printed. */
1799 pad_vertically = false;
1800 pv = false;
1802 lines_left_on_page = lines_per_body;
1803 if (double_space)
1804 lines_left_on_page *= 2;
1806 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1808 output_position = 0;
1809 spaces_not_printed = 0;
1810 separators_not_printed = 0;
1811 pad_vertically = false;
1812 align_empty_cols = false;
1813 empty_line = true;
1815 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1817 input_position = 0;
1818 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1820 FF_only = false;
1821 padding_not_printed = p->start_position;
1822 if (!(p->print_func) (p))
1823 read_rest_of_line (p);
1824 pv |= pad_vertically;
1826 --p->lines_to_print;
1827 if (p->lines_to_print <= 0)
1829 if (cols_ready_to_print () <= 0)
1830 break;
1833 /* File p changed its status to ON_HOLD or CLOSED */
1834 if (parallel_files && p->status != OPEN)
1836 if (empty_line)
1837 align_empty_cols = true;
1838 else if (p->status == CLOSED ||
1839 (p->status == ON_HOLD && FF_only))
1840 align_column (p);
1843 else if (parallel_files)
1845 /* File status ON_HOLD or CLOSED */
1846 if (empty_line)
1847 align_empty_cols = true;
1848 else
1849 align_column (p);
1852 /* We need it also with an empty column */
1853 if (use_col_separator)
1854 ++separators_not_printed;
1857 if (pad_vertically)
1859 putchar ('\n');
1860 --lines_left_on_page;
1863 if (cols_ready_to_print () <= 0 && !extremities)
1864 break;
1866 if (double_space && pv)
1868 putchar ('\n');
1869 --lines_left_on_page;
1873 if (lines_left_on_page == 0)
1874 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1875 if (p->status == OPEN)
1876 p->full_page_printed = true;
1878 pad_vertically = pv;
1880 if (pad_vertically && extremities)
1881 pad_down (lines_left_on_page + lines_per_footer);
1882 else if (keep_FF && print_a_FF)
1884 putchar ('\f');
1885 print_a_FF = false;
1888 if (last_page_number < page_number)
1889 return false; /* Stop printing with LAST_PAGE */
1891 reset_status (); /* Change ON_HOLD to OPEN. */
1893 return true; /* More pages to go. */
1896 /* Allocate space for storing columns.
1898 This is necessary when printing multiple columns from a single file.
1899 Lines are stored consecutively in buff, separated by '\0'.
1901 The following doesn't apply any longer - any tuning possible?
1902 (We can't use a fixed offset since with the '-s' flag lines aren't
1903 truncated.)
1905 We maintain a list (line_vector) of pointers to the beginnings
1906 of lines in buff. We allocate one more than the number of lines
1907 because the last entry tells us the index of the last character,
1908 which we need to know in order to print the last line in buff. */
1910 static void
1911 init_store_cols (void)
1913 int total_lines = lines_per_body * columns;
1914 int chars_if_truncate = total_lines * (chars_per_column + 1);
1916 free (line_vector);
1917 /* FIXME: here's where it was allocated. */
1918 line_vector = xmalloc ((total_lines + 1) * sizeof *line_vector);
1920 free (end_vector);
1921 end_vector = xmalloc (total_lines * sizeof *end_vector);
1923 free (buff);
1924 buff_allocated = (use_col_separator
1925 ? 2 * chars_if_truncate
1926 : chars_if_truncate); /* Tune this. */
1927 buff = xmalloc (buff_allocated);
1930 /* Store all but the rightmost column.
1931 (Used when printing a single file in multiple downward columns)
1933 For each column
1934 set p->current_line to be the index in line_vector of the
1935 first line in the column
1936 For each line in the column
1937 store the line in buff
1938 add to line_vector the index of the line's first char
1939 buff_start is the index in buff of the first character in the
1940 current line. */
1942 static void
1943 store_columns (void)
1945 int i, j;
1946 unsigned int line = 0;
1947 unsigned int buff_start;
1948 int last_col; /* The rightmost column which will be saved in buff */
1949 COLUMN *p;
1951 buff_current = 0;
1952 buff_start = 0;
1954 if (balance_columns)
1955 last_col = columns;
1956 else
1957 last_col = columns - 1;
1959 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1960 p->lines_stored = 0;
1962 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1963 ++i, ++p)
1965 p->current_line = line;
1966 for (j = lines_per_body; j && files_ready_to_read; --j)
1968 if (p->status == OPEN) /* Redundant. Clean up. */
1970 input_position = 0;
1972 if (!read_line (p))
1973 read_rest_of_line (p);
1975 if (p->status == OPEN
1976 || buff_start != buff_current)
1978 ++p->lines_stored;
1979 line_vector[line] = buff_start;
1980 end_vector[line++] = input_position;
1981 buff_start = buff_current;
1986 /* Keep track of the location of the last char in buff. */
1987 line_vector[line] = buff_start;
1989 if (balance_columns)
1990 balance (line);
1993 static void
1994 balance (int total_stored)
1996 COLUMN *p;
1997 int i, lines;
1998 int first_line = 0;
2000 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
2002 lines = total_stored / columns;
2003 if (i <= total_stored % columns)
2004 ++lines;
2006 p->lines_stored = lines;
2007 p->current_line = first_line;
2009 first_line += lines;
2013 /* Store a character in the buffer. */
2015 static void
2016 store_char (char c)
2018 if (buff_current >= buff_allocated)
2020 /* May be too generous. */
2021 buff = X2REALLOC (buff, &buff_allocated);
2023 buff[buff_current++] = c;
2026 static void
2027 add_line_number (COLUMN *p)
2029 int i;
2030 char *s;
2031 int left_cut;
2033 /* Cutting off the higher-order digits is more informative than
2034 lower-order cut off*/
2035 if (line_number < power_10)
2036 sprintf (number_buff, "%*d", chars_per_number, line_number);
2037 else
2039 left_cut = line_number % power_10;
2040 sprintf (number_buff, "%0*d", chars_per_number, left_cut);
2042 line_number++;
2043 s = number_buff;
2044 for (i = chars_per_number; i > 0; i--)
2045 (p->char_func) (*s++);
2047 if (columns > 1)
2049 /* Tabification is assumed for multiple columns, also for n-separators,
2050 but `default n-separator = TAB' hasn't been given priority over
2051 equal column_width also specified by POSIX. */
2052 if (number_separator == '\t')
2054 i = number_width - chars_per_number;
2055 while (i-- > 0)
2056 (p->char_func) (' ');
2058 else
2059 (p->char_func) (number_separator);
2061 else
2062 /* To comply with POSIX, we avoid any expansion of default TAB
2063 separator with a single column output. No column_width requirement
2064 has to be considered. */
2066 (p->char_func) (number_separator);
2067 if (number_separator == '\t')
2068 output_position = POS_AFTER_TAB (chars_per_output_tab,
2069 output_position);
2072 if (truncate_lines && !parallel_files)
2073 input_position += number_width;
2076 /* Print (or store) padding until the current horizontal position
2077 is position. */
2079 static void
2080 pad_across_to (int position)
2082 int h = output_position;
2084 if (tabify_output)
2085 spaces_not_printed = position - output_position;
2086 else
2088 while (++h <= position)
2089 putchar (' ');
2090 output_position = position;
2094 /* Pad to the bottom of the page.
2096 If the user has requested a formfeed, use one.
2097 Otherwise, use newlines. */
2099 static void
2100 pad_down (int lines)
2102 int i;
2104 if (use_form_feed)
2105 putchar ('\f');
2106 else
2107 for (i = lines; i; --i)
2108 putchar ('\n');
2111 /* Read the rest of the line.
2113 Read from the current column's file until an end of line is
2114 hit. Used when we've truncated a line and we no longer need
2115 to print or store its characters. */
2117 static void
2118 read_rest_of_line (COLUMN *p)
2120 int c;
2121 FILE *f = p->fp;
2123 while ((c = getc (f)) != '\n')
2125 if (c == '\f')
2127 if ((c = getc (f)) != '\n')
2128 ungetc (c, f);
2129 if (keep_FF)
2130 print_a_FF = true;
2131 hold_file (p);
2132 break;
2134 else if (c == EOF)
2136 close_file (p);
2137 break;
2142 /* Read a line with skip_to_page.
2144 Read from the current column's file until an end of line is
2145 hit. Used when we read full lines to skip pages.
2146 With skip_to_page we have to check for FF-coincidence which is done
2147 in function read_line otherwise.
2148 Count lines of skipped pages to find the line number of 1st page
2149 printed relative to 1st line of input file (start_line_num). */
2151 static void
2152 skip_read (COLUMN *p, int column_number)
2154 int c;
2155 FILE *f = p->fp;
2156 int i;
2157 bool single_ff = false;
2158 COLUMN *q;
2160 /* Read 1st character in a line or any character succeeding a FF */
2161 if ((c = getc (f)) == '\f' && p->full_page_printed)
2162 /* A FF-coincidence with a previous full_page_printed.
2163 To avoid an additional empty page, eliminate the FF */
2164 if ((c = getc (f)) == '\n')
2165 c = getc (f);
2167 p->full_page_printed = false;
2169 /* 1st character a FF means a single FF without any printable
2170 characters. Don't count it as a line with -n option. */
2171 if (c == '\f')
2172 single_ff = true;
2174 /* Preparing for a FF-coincidence: Maybe we finish that page
2175 without a FF found */
2176 if (last_line)
2177 p->full_page_printed = true;
2179 while (c != '\n')
2181 if (c == '\f')
2183 /* No FF-coincidence possible,
2184 no catching up of a FF-coincidence with next page */
2185 if (last_line)
2187 if (!parallel_files)
2188 for (q = column_vector, i = columns; i; ++q, --i)
2189 q->full_page_printed = false;
2190 else
2191 p->full_page_printed = false;
2194 if ((c = getc (f)) != '\n')
2195 ungetc (c, f);
2196 hold_file (p);
2197 break;
2199 else if (c == EOF)
2201 close_file (p);
2202 break;
2204 c = getc (f);
2207 if (skip_count)
2208 if ((!parallel_files || column_number == 1) && !single_ff)
2209 ++line_count;
2212 /* If we're tabifying output,
2214 When print_char encounters white space it keeps track
2215 of our desired horizontal position and delays printing
2216 until this function is called. */
2218 static void
2219 print_white_space (void)
2221 int h_new;
2222 int h_old = output_position;
2223 int goal = h_old + spaces_not_printed;
2225 while (goal - h_old > 1
2226 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2228 putchar (output_tab_char);
2229 h_old = h_new;
2231 while (++h_old <= goal)
2232 putchar (' ');
2234 output_position = goal;
2235 spaces_not_printed = 0;
2238 /* Print column separators.
2240 We keep a count until we know that we'll be printing a line,
2241 then print_sep_string() is called. */
2243 static void
2244 print_sep_string (void)
2246 char *s;
2247 int l = col_sep_length;
2249 s = col_sep_string;
2251 if (separators_not_printed <= 0)
2253 /* We'll be starting a line with chars_per_margin, anything else? */
2254 if (spaces_not_printed > 0)
2255 print_white_space ();
2257 else
2259 for (; separators_not_printed > 0; --separators_not_printed)
2261 while (l-- > 0)
2263 /* 3 types of sep_strings: spaces only, spaces and chars,
2264 chars only */
2265 if (*s == ' ')
2267 /* We're tabifying output; consecutive spaces in
2268 sep_string may have to be converted to tabs */
2269 s++;
2270 ++spaces_not_printed;
2272 else
2274 if (spaces_not_printed > 0)
2275 print_white_space ();
2276 putchar (*s++);
2277 ++output_position;
2280 /* sep_string ends with some spaces */
2281 if (spaces_not_printed > 0)
2282 print_white_space ();
2287 /* Print (or store, depending on p->char_func) a clump of N
2288 characters. */
2290 static void
2291 print_clump (COLUMN *p, int n, char *clump)
2293 while (n--)
2294 (p->char_func) (*clump++);
2297 /* Print a character.
2299 Update the following comment: process-char hasn't been used any
2300 longer.
2301 If we're tabifying, all tabs have been converted to spaces by
2302 process_char(). Keep a count of consecutive spaces, and when
2303 a nonspace is encountered, call print_white_space() to print the
2304 required number of tabs and spaces. */
2306 static void
2307 print_char (char c)
2309 if (tabify_output)
2311 if (c == ' ')
2313 ++spaces_not_printed;
2314 return;
2316 else if (spaces_not_printed > 0)
2317 print_white_space ();
2319 /* Nonprintables are assumed to have width 0, except '\b'. */
2320 if (! isprint (to_uchar (c)))
2322 if (c == '\b')
2323 --output_position;
2325 else
2326 ++output_position;
2328 putchar (c);
2331 /* Skip to page PAGE before printing.
2332 PAGE may be larger than total number of pages. */
2334 static bool
2335 skip_to_page (uintmax_t page)
2337 uintmax_t n;
2338 int i;
2339 int j;
2340 COLUMN *p;
2342 for (n = 1; n < page; ++n)
2344 for (i = 1; i < lines_per_body; ++i)
2346 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2347 if (p->status == OPEN)
2348 skip_read (p, j);
2350 last_line = true;
2351 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2352 if (p->status == OPEN)
2353 skip_read (p, j);
2355 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2356 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2357 if (p->status != CLOSED)
2358 p->status = ON_HOLD;
2360 reset_status ();
2361 last_line = false;
2363 if (files_ready_to_read < 1)
2365 /* It's very helpful, normally the total number of pages is
2366 not known in advance. */
2367 error (0, 0,
2368 _("starting page number %"PRIuMAX
2369 " exceeds page count %"PRIuMAX),
2370 page, n);
2371 break;
2374 return files_ready_to_read > 0;
2377 /* Print a header.
2379 Formfeeds are assumed to use up two lines at the beginning of
2380 the page. */
2382 static void
2383 print_header (void)
2385 char page_text[256 + INT_STRLEN_BOUND (page_number)];
2386 int available_width;
2387 int lhs_spaces;
2388 int rhs_spaces;
2390 output_position = 0;
2391 pad_across_to (chars_per_margin);
2392 print_white_space ();
2394 if (page_number == 0)
2395 error (EXIT_FAILURE, 0, _("page number overflow"));
2397 /* The translator must ensure that formatting the translation of
2398 "Page %"PRIuMAX does not generate more than (sizeof page_text - 1)
2399 bytes. */
2400 sprintf (page_text, _("Page %"PRIuMAX), page_number++);
2401 available_width = header_width_available - mbswidth (page_text, 0);
2402 available_width = MAX (0, available_width);
2403 lhs_spaces = available_width >> 1;
2404 rhs_spaces = available_width - lhs_spaces;
2406 printf ("\n\n%*s%s%*s%s%*s%s\n\n\n",
2407 chars_per_margin, "",
2408 date_text, lhs_spaces, " ",
2409 file_text, rhs_spaces, " ", page_text);
2411 print_a_header = false;
2412 output_position = 0;
2415 /* Print (or store, if p->char_func is store_char()) a line.
2417 Read a character to determine whether we have a line or not.
2418 (We may hit EOF, \n, or \f)
2420 Once we know we have a line,
2421 set pad_vertically = true, meaning it's safe
2422 to pad down at the end of the page, since we do have a page.
2423 print a header if needed.
2424 pad across to padding_not_printed if needed.
2425 print any separators which need to be printed.
2426 print a line number if it needs to be printed.
2428 Print the clump which corresponds to the first character.
2430 Enter a loop and keep printing until an end of line condition
2431 exists, or until we exceed chars_per_column.
2433 Return false if we exceed chars_per_column before reading
2434 an end of line character, true otherwise. */
2436 static bool
2437 read_line (COLUMN *p)
2439 int c;
2440 int chars IF_LINT ( = 0);
2441 int last_input_position;
2442 int j, k;
2443 COLUMN *q;
2445 /* read 1st character in each line or any character succeeding a FF: */
2446 c = getc (p->fp);
2448 last_input_position = input_position;
2450 if (c == '\f' && p->full_page_printed)
2451 if ((c = getc (p->fp)) == '\n')
2452 c = getc (p->fp);
2453 p->full_page_printed = false;
2455 switch (c)
2457 case '\f':
2458 if ((c = getc (p->fp)) != '\n')
2459 ungetc (c, p->fp);
2460 FF_only = true;
2461 if (print_a_header && !storing_columns)
2463 pad_vertically = true;
2464 print_header ();
2466 else if (keep_FF)
2467 print_a_FF = true;
2468 hold_file (p);
2469 return true;
2470 case EOF:
2471 close_file (p);
2472 return true;
2473 case '\n':
2474 break;
2475 default:
2476 chars = char_to_clump (c);
2479 if (truncate_lines && input_position > chars_per_column)
2481 input_position = last_input_position;
2482 return false;
2485 if (p->char_func != store_char)
2487 pad_vertically = true;
2489 if (print_a_header && !storing_columns)
2490 print_header ();
2492 if (parallel_files && align_empty_cols)
2494 /* We have to align empty columns at the beginning of a line. */
2495 k = separators_not_printed;
2496 separators_not_printed = 0;
2497 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2499 align_column (q);
2500 separators_not_printed += 1;
2502 padding_not_printed = p->start_position;
2503 if (truncate_lines)
2504 spaces_not_printed = chars_per_column;
2505 else
2506 spaces_not_printed = 0;
2507 align_empty_cols = false;
2510 if (padding_not_printed - col_sep_length > 0)
2512 pad_across_to (padding_not_printed - col_sep_length);
2513 padding_not_printed = ANYWHERE;
2516 if (use_col_separator)
2517 print_sep_string ();
2520 if (p->numbered)
2521 add_line_number (p);
2523 empty_line = false;
2524 if (c == '\n')
2525 return true;
2527 print_clump (p, chars, clump_buff);
2529 while (true)
2531 c = getc (p->fp);
2533 switch (c)
2535 case '\n':
2536 return true;
2537 case '\f':
2538 if ((c = getc (p->fp)) != '\n')
2539 ungetc (c, p->fp);
2540 if (keep_FF)
2541 print_a_FF = true;
2542 hold_file (p);
2543 return true;
2544 case EOF:
2545 close_file (p);
2546 return true;
2549 last_input_position = input_position;
2550 chars = char_to_clump (c);
2551 if (truncate_lines && input_position > chars_per_column)
2553 input_position = last_input_position;
2554 return false;
2557 print_clump (p, chars, clump_buff);
2561 /* Print a line from buff.
2563 If this function has been called, we know we have "something to
2564 print". But it remains to be seen whether we have a real text page
2565 or an empty page (a single form feed) with/without a header only.
2566 Therefore first we set pad_vertically to true and print a header
2567 if necessary.
2568 If FF_FOUND and we are using -t|-T option we omit any newline by
2569 setting pad_vertically to false (see print_page).
2570 Otherwise we pad across if necessary, print separators if necessary
2571 and text of COLUMN *p.
2573 Return true, meaning there is no need to call read_rest_of_line. */
2575 static bool
2576 print_stored (COLUMN *p)
2578 COLUMN *q;
2579 int i;
2581 int line = p->current_line++;
2582 char *first = &buff[line_vector[line]];
2583 /* FIXME
2584 UMR: Uninitialized memory read:
2585 * This is occurring while in:
2586 print_stored [pr.c:2239]
2587 * Reading 4 bytes from 0x5148c in the heap.
2588 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2589 * This block was allocated from:
2590 malloc [rtlib.o]
2591 xmalloc [xmalloc.c:94]
2592 init_store_cols [pr.c:1648]
2594 char *last = &buff[line_vector[line + 1]];
2596 pad_vertically = true;
2598 if (print_a_header)
2599 print_header ();
2601 if (p->status == FF_FOUND)
2603 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2604 q->status = ON_HOLD;
2605 if (column_vector->lines_to_print <= 0)
2607 if (!extremities)
2608 pad_vertically = false;
2609 return true; /* print a header only */
2613 if (padding_not_printed - col_sep_length > 0)
2615 pad_across_to (padding_not_printed - col_sep_length);
2616 padding_not_printed = ANYWHERE;
2619 if (use_col_separator)
2620 print_sep_string ();
2622 while (first != last)
2623 print_char (*first++);
2625 if (spaces_not_printed == 0)
2627 output_position = p->start_position + end_vector[line];
2628 if (p->start_position - col_sep_length == chars_per_margin)
2629 output_position -= col_sep_length;
2632 return true;
2635 /* Convert a character to the proper format and return the number of
2636 characters in the resulting clump. Increment input_position by
2637 the width of the clump.
2639 Tabs are converted to clumps of spaces.
2640 Nonprintable characters may be converted to clumps of escape
2641 sequences or control prefixes.
2643 Note: the width of a clump is not necessarily equal to the number of
2644 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2645 number of characters is 1.) */
2647 static int
2648 char_to_clump (char c)
2650 unsigned char uc = c;
2651 char *s = clump_buff;
2652 int i;
2653 char esc_buff[4];
2654 int width;
2655 int chars;
2656 int chars_per_c = 8;
2658 if (c == input_tab_char)
2659 chars_per_c = chars_per_input_tab;
2661 if (c == input_tab_char || c == '\t')
2663 width = TAB_WIDTH (chars_per_c, input_position);
2665 if (untabify_input)
2667 for (i = width; i; --i)
2668 *s++ = ' ';
2669 chars = width;
2671 else
2673 *s = c;
2674 chars = 1;
2678 else if (! isprint (uc))
2680 if (use_esc_sequence)
2682 width = 4;
2683 chars = 4;
2684 *s++ = '\\';
2685 sprintf (esc_buff, "%03o", uc);
2686 for (i = 0; i <= 2; ++i)
2687 *s++ = esc_buff[i];
2689 else if (use_cntrl_prefix)
2691 if (uc < 0200)
2693 width = 2;
2694 chars = 2;
2695 *s++ = '^';
2696 *s++ = c ^ 0100;
2698 else
2700 width = 4;
2701 chars = 4;
2702 *s++ = '\\';
2703 sprintf (esc_buff, "%03o", uc);
2704 for (i = 0; i <= 2; ++i)
2705 *s++ = esc_buff[i];
2708 else if (c == '\b')
2710 width = -1;
2711 chars = 1;
2712 *s = c;
2714 else
2716 width = 0;
2717 chars = 1;
2718 *s = c;
2721 else
2723 width = 1;
2724 chars = 1;
2725 *s = c;
2728 /* Too many backspaces must put us in position 0 -- never negative. */
2729 if (width < 0 && input_position == 0)
2731 chars = 0;
2732 input_position = 0;
2734 else if (width < 0 && input_position <= -width)
2735 input_position = 0;
2736 else
2737 input_position += width;
2739 return chars;
2742 /* We've just printed some files and need to clean up things before
2743 looking for more options and printing the next batch of files.
2745 Free everything we've xmalloc'ed, except `header'. */
2747 static void
2748 cleanup (void)
2750 free (number_buff);
2751 free (clump_buff);
2752 free (column_vector);
2753 free (line_vector);
2754 free (end_vector);
2755 free (buff);
2758 /* Complain, print a usage message, and die. */
2760 void
2761 usage (int status)
2763 if (status != EXIT_SUCCESS)
2764 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2765 program_name);
2766 else
2768 printf (_("\
2769 Usage: %s [OPTION]... [FILE]...\n\
2771 program_name);
2773 fputs (_("\
2774 Paginate or columnate FILE(s) for printing.\n\
2776 "), stdout);
2777 fputs (_("\
2778 Mandatory arguments to long options are mandatory for short options too.\n\
2779 "), stdout);
2780 fputs (_("\
2781 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2782 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2783 -COLUMN, --columns=COLUMN\n\
2784 output COLUMN columns and print columns down,\n\
2785 unless -a is used. Balance number of lines in the\n\
2786 columns on each page\n\
2787 "), stdout);
2788 fputs (_("\
2789 -a, --across print columns across rather than down, used together\n\
2790 with -COLUMN\n\
2791 -c, --show-control-chars\n\
2792 use hat notation (^G) and octal backslash notation\n\
2793 -d, --double-space\n\
2794 double space the output\n\
2795 "), stdout);
2796 fputs (_("\
2797 -D, --date-format=FORMAT\n\
2798 use FORMAT for the header date\n\
2799 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2800 expand input CHARs (TABs) to tab WIDTH (8)\n\
2801 -F, -f, --form-feed\n\
2802 use form feeds instead of newlines to separate pages\n\
2803 (by a 3-line page header with -F or a 5-line header\n\
2804 and trailer without -F)\n\
2805 "), stdout);
2806 fputs (_("\
2807 -h, --header=HEADER\n\
2808 use a centered HEADER instead of filename in page header,\n\
2809 -h \"\" prints a blank line, don't use -h\"\"\n\
2810 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2811 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2812 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2813 alignment, --sep-string[=STRING] sets separators\n\
2814 "), stdout);
2815 fputs (_("\
2816 -l, --length=PAGE_LENGTH\n\
2817 set the page length to PAGE_LENGTH (66) lines\n\
2818 (default number of lines of text 56, and with -F 63)\n\
2819 -m, --merge print all files in parallel, one in each column,\n\
2820 truncate lines, but join lines of full length with -J\n\
2821 "), stdout);
2822 fputs (_("\
2823 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2824 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2825 default counting starts with 1st line of input file\n\
2826 -N, --first-line-number=NUMBER\n\
2827 start counting with NUMBER at 1st line of first\n\
2828 page printed (see +FIRST_PAGE)\n\
2829 "), stdout);
2830 fputs (_("\
2831 -o, --indent=MARGIN\n\
2832 offset each line with MARGIN (zero) spaces, do not\n\
2833 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2834 -r, --no-file-warnings\n\
2835 omit warning when a file cannot be opened\n\
2836 "), stdout);
2837 fputs (_("\
2838 -s[CHAR], --separator[=CHAR]\n\
2839 separate columns by a single character, default for CHAR\n\
2840 is the <TAB> character without -w and \'no char\' with -w\n\
2841 -s[CHAR] turns off line truncation of all 3 column\n\
2842 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2843 "), stdout);
2844 fputs (_("\
2845 -SSTRING, --sep-string[=STRING]\n\
2846 separate columns by STRING,\n\
2847 without -S: Default separator <TAB> with -J and <space>\n\
2848 otherwise (same as -S\" \"), no effect on column options\n\
2849 -t, --omit-header omit page headers and trailers\n\
2850 "), stdout);
2851 fputs (_("\
2852 -T, --omit-pagination\n\
2853 omit page headers and trailers, eliminate any pagination\n\
2854 by form feeds set in input files\n\
2855 -v, --show-nonprinting\n\
2856 use octal backslash notation\n\
2857 -w, --width=PAGE_WIDTH\n\
2858 set page width to PAGE_WIDTH (72) characters for\n\
2859 multiple text-column output only, -s[char] turns off (72)\n\
2860 "), stdout);
2861 fputs (_("\
2862 -W, --page-width=PAGE_WIDTH\n\
2863 set page width to PAGE_WIDTH (72) characters always,\n\
2864 truncate lines, except -J option is set, no interference\n\
2865 with -S or -s\n\
2866 "), stdout);
2867 fputs (HELP_OPTION_DESCRIPTION, stdout);
2868 fputs (VERSION_OPTION_DESCRIPTION, stdout);
2869 fputs (_("\
2871 -t is implied if PAGE_LENGTH <= 10. With no FILE, or when FILE is -, read\n\
2872 standard input.\n\
2873 "), stdout);
2874 emit_ancillary_info ();
2876 exit (status);