*** empty log message ***
[coreutils.git] / src / pr.c
blob9149f3f47b39ee313f2ac9af12d18f6d122b7f55
1 /* pr -- convert text files for printing.
2 Copyright (C) 88, 91, 1995-1999 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 2, or (at your option)
7 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, write to the Free Software Foundation,
16 Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
18 /* By Pete TerMaat, with considerable refinement by Roland Huebner. */
20 /* Things to watch: Sys V screws up on ...
21 pr -n -3 -s: /usr/dict/words
22 pr -m -o10 -n /usr/dict/words{,,,}
23 pr -6 -a -n -o5 /usr/dict/words
25 Ideas:
27 Keep a things_to_do list of functions to call when we know we have
28 something to print. Cleaner than current series of checks.
30 Improve the printing of control prefixes.
32 Expand the filename in the centered header line to a full pathname.
35 Concept:
37 If the input_tab_char differs from the default value TAB
38 (`-e[CHAR[...]]' is used), any input text tab is expanded to the
39 default width of 8 spaces (compare char_to_clump). - Same as SunOS
40 does.
42 The treatment of the number_separator (compare add_line_number):
43 The default value TAB of the number_separator (`-n[SEP[...]]') doesn't
44 be thought to be an input character. An optional `-e'-input has no
45 effect.
46 - With single column output
47 only one POSIX requirement has to be met:
48 The default n-separator should be a TAB. The consequence is a
49 different width between the number an the text if the output position
50 of the separator changes, i.e. it depends upon the left margin used.
51 That's not nice but easy-to-use together with the defaults of other
52 utilities, e.g. sort or cut. - Same as SunOS does.
53 - With multicolumn output
54 two conflicting POSIX requirements exist:
55 First `default n-separator is TAB', second `output text columns shall
56 be of equal width'. Moreover POSIX specifies the number+separator a
57 part of the column, together with `-COLUMN' and `-a -COLUMN'.
58 (With -m output the number shall occupy each line only once. Exactly
59 the same situation as single column output exists.)
60 GNU pr gives priority to the 2nd requirement and observes POSIX
61 column definition. The n-separator TAB is expanded to the same number
62 of spaces in each column using the default value 8. Tabification is
63 only performed if it is compatible with the output position.
64 Consequence: The output text columns are of equal width. The layout
65 of a page does not change if the left margin varies. - Looks better
66 than the SunOS approach.
67 SunOS pr gives priority to the 1st requirement. n-separator TAB
68 width varies with each column. Only the width of text part of the
69 column is fixed.
70 Consequence: The output text columns don't have equal width. The
71 widths and the layout of the whole page varies with the left margin.
72 An overflow of the line length (without margin) over the input value
73 PAGE_WIDTH may occur.
75 The interference of the POSIX-compliant small letter options -w and -s:
76 (`interference' means `setting a _separator_ with -s switches off the
77 column sturctur and the default - not generally - page_width,
78 acts on -w option')
79 options: text form / separator: equivalent new capital
80 -w l -s[x] letter options:
81 --------------------------------------------------------------------
82 1. -- -- columns / space --
83 trunc. to page_width = 72
84 2. -- -s[:] full lines / TAB[:] -J -S["<TAB>"|:]
85 no truncation
86 3. -w l -- columns / space -W l
87 trunc. to page_width = l
88 4. -w l -s[:] columns / no sep.[:] -W l -S[:]
89 trunc. to page_width = l
90 --------------------------------------------------------------------
93 Options:
95 Including version 1.22i:
96 Some SMALL LETTER options has been redefined with the object of a
97 better POSIX compliance. The output of some further cases has been
98 adapted to other UNIXes. A violation of downward compatibility has to
99 be accepted.
100 Some NEW CAPITAL LETTER options ( -J, -S, -W) has been introduced to
101 turn off unexpected interferences of small letter options (-s and -w
102 together with the three column options).
103 -N option and the second argument LAST_PAGE of +FIRST_PAGE offer more
104 flexibility; The detailed handling of form feeds set in the input
105 files requires -T option.
107 Capital letter options dominate small letter ones.
109 Some of the option-arguments cannot be specified as separate arguments
110 from the preceding option letter (already stated in POSIX specification).
112 Form feeds in the input cause page breaks in the output. Multiple
113 form feeds produce empty pages.
115 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]
116 begin [stop] printing with page FIRST_[LAST_]PAGE
118 -COLUMN, --columns=COLUMN
119 Produce output that is COLUMN columns wide and
120 print columns down, unless -a is used. Balance number of
121 lines in the columns on each page.
123 -a, --across Print columns across rather than down, used
124 together with -COLUMN. The input
127 three
128 four
129 will be printed with `-a -3' as
130 one two three
131 four
133 -b Balance columns on the last page.
134 -b is no longer an independent option. It's always used
135 together with -COLUMN (unless -a is used) to get a
136 consistent formulation with "FF set by hand" in input
137 files. Each formfeed found terminates the number of lines
138 to be read with the actual page. The situation for
139 printing columns down is equivalent to that on the last
140 page. So we need a balancing.
142 Keeping -b as an underground option guarantees some
143 downward compatibility. Utilities using pr with -b
144 (a most frequently used form) still work as usual.
146 -c, --show-control-chars
147 Print unprintable characters as control prefixes.
148 Control-g is printed as ^G (use hat notation) and
149 octal backslash notation.
151 -d, --double-space Double space the output.
153 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]
154 Expand tabs to spaces on input. Optional argument CHAR
155 is the input TAB character. (Default is TAB). Optional
156 argument WIDTH is the input TAB character's width.
157 (Default is 8.)
159 -F, -f, --form-feed Use formfeeds instead of newlines to separate
160 pages. A three line HEADER is used, no TRAILER with -F,
161 without -F both HEADER and TRAILER are made of five lines.
163 -h HEADER, --header=HEADER
164 Replace the filename in the header with the string HEADER.
165 Checking and left-hand-side truncation of the length of the
166 standard and custom header string. A centered header is used.
167 The format of date and time has been shortened
168 to yyyy-mm-dd HH:MM to give place to a maximal filename
169 information.
170 -h "" now prints a blank line header. -h"" shows an error.
172 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]
173 Replace spaces with tabs on output. Optional argument
174 CHAR is the output TAB character. (Default is TAB).
175 Optional argument WIDTH is the output TAB character's
176 width. (Default is 8)
178 -J, --join-lines Merge lines of full length, turns off -W/-w
179 line truncation, no column alignment, -S[STRING] sets
180 separators, works with all column options
181 (-COLUMN | -a -COLUMN | -m).
182 -J has been introduced (together with -W and -S) to
183 disentangle the old (POSIX compliant) options -w, -s
184 along with the 3 column options.
186 -l PAGE_LENGTH, --length=PAGE_LENGTH
187 Set the page length to PAGE_LENGTH lines. Default is 66,
188 including 5 lines of HEADER and 5 lines of TRAILER
189 without -F, but only 3 lines of HEADER and no TRAILER
190 with -F (i.e the number of text lines defaults to 56 or
191 63 respectively).
193 -m, --merge Print files in parallel; pad_across_to align
194 columns; truncate lines and print separator strings;
195 Do it also with empty columns to get a continuous line
196 numbering and column marking by separators throughout
197 the whole merged file.
199 Empty pages in some input files produce empty columns
200 [marked by separators] in the merged pages. Completely
201 empty merged pages show no column separators at all.
203 The layout of a merged page is ruled by the largest form
204 feed distance of the single pages at that page. Shorter
205 columns will be filled up with empty lines.
207 Together with -J option join lines of full length and
208 set separators when -S option is used.
210 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]
211 Provide DIGITS digit line numbering (default for DIGITS
212 is 5). With multicolumn output the number occupies the
213 first DIGITS column positions of each text column or only
214 each line of -m output.
215 With single column output the number precedes each line
216 just as -m output.
217 Optional argument SEP is the character appended to the
218 line number to separate it from the text followed.
219 The default separator is a TAB. In a strict sense a TAB
220 is always printed with single column output only. The
221 TAB-width varies with the TAB-position, e.g. with the
222 left margin specified by -o option.
223 With multicolumn output priority is given to `equal width
224 of output columns' (a POSIX specification). The TAB-width
225 is fixed to the value of the 1st column and does not
226 change with different values of left margin. That means a
227 fixed number of spaces is always printed in the place of
228 a TAB. The tabification depends upon the output
229 position.
231 Default counting of the line numbers starts with 1st
232 line of the input file (not the 1st line printed,
233 compare the --page option and -N option).
235 -N NUMBER, --first-line-number=NUMBER
236 Start line counting with the number NUMBER at the 1st
237 line of first page printed (mostly not the 1st line of
238 the input file).
240 -o MARGIN, --indent=MARGIN
241 Offset each line with a margin MARGIN spaces wide.
242 Total page width is the size of the margin plus the
243 PAGE_WIDTH set with -W/-w option.
245 -r, --no-file-warnings
246 Omit warning when a file cannot be opened.
248 -s[CHAR], --separator[=CHAR]
249 Separate columns by a single character CHAR, default for
250 CHAR is the TAB character without -w and 'no char' with -w.
251 Without `-s' default separator `space' is set.
252 -s[CHAR] turns off line truncation of all 3 column options
253 (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX
254 compliant formulation. The source code translates -s into
255 the new options -S and -J, also -W if required.
257 -S[STRING], --sep-string[=STRING]
258 Separate columns by any string STRING. The -S option
259 doesn't react upon the -W/-w option (unlike -s option
260 does). It defines a separator nothing else.
261 Without -S: Default separator TAB is used with -J and
262 `space' otherwise (same as -S" ").
263 With -S only: No separator is used, same as -S"".
264 Quotes should be used with blanks and some shell active
265 characters.
266 Don't use -S "STRING". Some of the options don't allow the
267 option letter to be separated from its argument. -S/-s is
268 one of them. That's POSIX compliant.
270 -t, --omit-header Do not print headers or footers but retain form
271 feeds set in the input files.
273 -T, --omit-pagination
274 Do not print headers or footers, eliminate any pagination
275 by form feeds set in the input files.
277 -v, --show-nonprinting
278 Print unprintable characters as escape sequences. Use
279 octal backslash notation. Control-G becomes \007.
281 -w PAGE_WIDTH, --width=PAGE_WIDTH
282 Set page width to PAGE_WIDTH characters for multiple
283 text-column output only (default for PAGE_WIDTH is 72).
284 -s[CHAR] turns off the default page width and any line
285 truncation. Lines of full length will be merged,
286 regardless of the column options set. A POSIX compliant
287 formulation.
289 -W PAGE_WIDTH, --page-width=PAGE_WIDTH
290 Set the page width to PAGE_WIDTH characters. That's valid
291 with and without a column option. Text lines will be
292 truncated, unless -J is used. Together with one of the
293 column options (-COLUMN| -a -COLUMN| -m) column alignment
294 is always used.
295 Default is 72 characters.
296 Without -W PAGE_WIDTH
297 - but with one of the column options default truncation of
298 72 characters is used (to keep downward compatibility
299 and to simplify most frequently met column tasks).
300 Column alignment and column separators are used.
301 - and without any of the column options NO line truncation
302 is used (to keep downward compatibility and to meet most
303 frequent tasks). That's equivalent to -W 72 -J .
305 With/without -W PAGE_WIDTH the header line is always
306 truncated to avoid line overflow.
308 (In pr versions newer than 1.14 -S option does no longer
309 affect -W option.)
314 #include <config.h>
316 #include <stdio.h>
317 #include <getopt.h>
318 #include <sys/types.h>
319 #include <time.h>
320 #include "system.h"
321 #include "error.h"
322 #include "xstrtol.h"
324 /* The official name of this program (e.g., no `g' prefix). */
325 #define PROGRAM_NAME "pr"
327 #define AUTHORS "Pete TerMaat and Roland Huebner"
329 #ifndef TRUE
330 # define TRUE 1
331 # define FALSE 0
332 #endif
334 /* Used with start_position in the struct COLUMN described below.
335 If start_position == ANYWHERE, we aren't truncating columns and
336 can begin printing a column anywhere. Otherwise we must pad to
337 the horizontal position start_position. */
338 #define ANYWHERE 0
340 /* Each column has one of these structures allocated for it.
341 If we're only dealing with one file, fp is the same for all
342 columns.
344 The general strategy is to spend time setting up these column
345 structures (storing columns if necessary), after which printing
346 is a matter of flitting from column to column and calling
347 print_func.
349 Parallel files, single files printing across in multiple
350 columns, and single files printing down in multiple columns all
351 fit the same printing loop.
353 print_func Function used to print lines in this column.
354 If we're storing this column it will be
355 print_stored(), Otherwise it will be read_line().
357 char_func Function used to process characters in this column.
358 If we're storing this column it will be store_char(),
359 otherwise it will be print_char().
361 current_line Index of the current entry in line_vector, which
362 contains the index of the first character of the
363 current line in buff[].
365 lines_stored Number of lines in this column which are stored in
366 buff.
368 lines_to_print If we're storing this column, lines_to_print is
369 the number of stored_lines which remain to be
370 printed. Otherwise it is the number of lines
371 we can print without exceeding lines_per_body.
373 start_position The horizontal position we want to be in before we
374 print the first character in this column.
376 numbered True means precede this column with a line number. */
378 struct COLUMN
380 FILE *fp; /* Input stream for this column. */
381 char *name; /* File name. */
382 enum
384 OPEN,
385 FF_FOUND, /* used with -b option, set with \f, changed
386 to ON_HOLD after print_header */
387 ON_HOLD, /* Hit a form feed. */
388 CLOSED
390 status; /* Status of the file pointer. */
391 int (*print_func) (); /* Func to print lines in this col. */
392 void (*char_func) (); /* Func to print/store chars in this col. */
393 int current_line; /* Index of current place in line_vector. */
394 int lines_stored; /* Number of lines stored in buff. */
395 int lines_to_print; /* No. lines stored or space left on page. */
396 int start_position; /* Horizontal position of first char. */
397 int numbered;
398 int full_page_printed; /* True means printed without a FF found. */
400 /* p->full_page_printed controls a special case of "FF set by hand":
401 True means a full page has been printed without FF found. To avoid an
402 additional empty page we have to ignore a FF immediately following in
403 the next line. */
406 typedef struct COLUMN COLUMN;
408 #define NULLCOL (COLUMN *)0
410 static int char_to_clump PARAMS ((int c));
411 static int read_line PARAMS ((COLUMN *p));
412 static int print_page PARAMS ((void));
413 static int print_stored PARAMS ((COLUMN *p));
414 static int open_file PARAMS ((char *name, COLUMN *p));
415 static int skip_to_page PARAMS ((int page));
416 static void print_header PARAMS ((void));
417 static void pad_across_to PARAMS ((int position));
418 static void add_line_number PARAMS ((COLUMN *p));
419 static void getoptarg PARAMS ((char *arg, char switch_char, char *character,
420 int *number));
421 void usage PARAMS ((int status));
422 static void print_files PARAMS ((int number_of_files, char **av));
423 static void init_parameters PARAMS ((int number_of_files));
424 static void init_header PARAMS ((char *filename, int desc));
425 static int init_fps PARAMS ((int number_of_files, char **av));
426 static void init_funcs PARAMS ((void));
427 static void init_store_cols PARAMS ((void));
428 static void store_columns PARAMS ((void));
429 static void balance PARAMS ((int total_stored));
430 static void store_char PARAMS ((int c));
431 static void pad_down PARAMS ((int lines));
432 static void read_rest_of_line PARAMS ((COLUMN *p));
433 static void skip_read PARAMS ((COLUMN *p, int column_number));
434 static void print_char PARAMS ((int c));
435 static void cleanup PARAMS ((void));
436 static void first_last_page PARAMS ((char *pages));
437 static void print_sep_string PARAMS ((void));
438 static void separator_string PARAMS ((const char *optarg_S));
440 /* The name under which this program was invoked. */
441 char *program_name;
443 /* All of the columns to print. */
444 static COLUMN *column_vector;
446 /* When printing a single file in multiple downward columns,
447 we store the leftmost columns contiguously in buff.
448 To print a line from buff, get the index of the first character
449 from line_vector[i], and print up to line_vector[i + 1]. */
450 static char *buff;
452 /* Index of the position in buff where the next character
453 will be stored. */
454 static int buff_current;
456 /* The number of characters in buff.
457 Used for allocation of buff and to detect overflow of buff. */
458 static int buff_allocated;
460 /* Array of indices into buff.
461 Each entry is an index of the first character of a line.
462 This is used when storing lines to facilitate shuffling when
463 we do column balancing on the last page. */
464 static int *line_vector;
466 /* Array of horizonal positions.
467 For each line in line_vector, end_vector[line] is the horizontal
468 position we are in after printing that line. We keep track of this
469 so that we know how much we need to pad to prepare for the next
470 column. */
471 static int *end_vector;
473 /* (-m) True means we're printing multiple files in parallel. */
474 static int parallel_files = FALSE;
476 /* (-m) True means a line starts with some empty columns (some files
477 already CLOSED or ON_HOLD) which we have to align. */
478 static int align_empty_cols;
480 /* (-m) True means we have not yet found any printable column in a line.
481 align_empty_cols = TRUE has to be maintained. */
482 static int empty_line;
484 /* (-m) False means printable column output precedes a form feed found.
485 Column alignment is done only once. No additional action with that form
486 feed.
487 True means we found only a form feed in a column. Maybe we have to do
488 some column alignment with that form feed. */
489 static int FF_only;
491 /* (-[0-9]+) True means we're given an option explicitly specifying
492 number of columns. Used to detect when this option is used with -m
493 and when translating old options to new/long options. */
494 static int explicit_columns = FALSE;
496 /* (-t|-T) False means we aren't printing headers and footers. */
497 static int extremities = TRUE;
499 /* (-t) True means we retain all FF set by hand in input files.
500 False is set with -T option. */
501 static int keep_FF = FALSE;
502 static int print_a_FF = FALSE;
504 /* True means we need to print a header as soon as we know we've got input
505 to print after it. */
506 static int print_a_header;
508 /* (-h) True means we're using the standard header rather than a
509 customized one specified by the -h flag. */
510 static int standard_header = TRUE;
512 /* (-f) True means use formfeeds instead of newlines to separate pages. */
513 static int use_form_feed = FALSE;
515 /* True means we have read the standard input. */
516 static int have_read_stdin = FALSE;
518 /* True means the -a flag has been given. */
519 static int print_across_flag = FALSE;
521 /* True means we're printing one file in multiple (>1) downward columns. */
522 static int storing_columns = TRUE;
524 /* (-b) True means balance columns on the last page as Sys V does. */
525 /* That's no longer an independent option. With storing_columns = TRUE
526 balance_columns = TRUE is used too (s. function init_parameters).
527 We get a consistent formulation with "FF set by hand" in input files. */
528 static int balance_columns = FALSE;
530 /* (-l) Number of lines on a page, including header and footer lines. */
531 static int lines_per_page = 66;
533 /* Number of lines in the header and footer can be reset to 0 using
534 the -t flag. */
535 static int lines_per_header = 5;
536 static int lines_per_body;
537 static int lines_per_footer = 5;
539 /* (-w|-W) Width in characters of the page. Does not include the width of
540 the margin. */
541 static int chars_per_line = 72;
543 /* (-w|W) True means we truncate lines longer than chars_per_column. */
544 static int truncate_lines = FALSE;
546 /* (-J) True means we join lines without any line truncation. -J
547 dominates -w option. */
548 static int join_lines = FALSE;
550 /* Number of characters in a column. Based on col_sep_length and
551 page width. */
552 static int chars_per_column;
554 /* (-e) True means convert tabs to spaces on input. */
555 static int untabify_input = FALSE;
557 /* (-e) The input tab character. */
558 static char input_tab_char = '\t';
560 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
561 where the leftmost column is 1. */
562 static int chars_per_input_tab = 8;
564 /* (-i) True means convert spaces to tabs on output. */
565 static int tabify_output = FALSE;
567 /* (-i) The output tab character. */
568 static char output_tab_char = '\t';
570 /* (-i) The width of the output tab. */
571 static int chars_per_output_tab = 8;
573 /* Keeps track of pending white space. When we hit a nonspace
574 character after some whitespace, we print whitespace, tabbing
575 if necessary to get to output_position + spaces_not_printed. */
576 static int spaces_not_printed;
578 /* (-o) Number of spaces in the left margin (tabs used when possible). */
579 static int chars_per_margin = 0;
581 /* Position where the next character will fall.
582 Leftmost position is 0 + chars_per_margin.
583 Rightmost position is chars_per_margin + chars_per_line - 1.
584 This is important for converting spaces to tabs on output. */
585 static int output_position;
587 /* Horizontal position relative to the current file.
588 (output_position depends on where we are on the page;
589 input_position depends on where we are in the file.)
590 Important for converting tabs to spaces on input. */
591 static int input_position;
593 /* Count number of failed opens so we can exit with nonzero
594 status if there were any. */
595 static int failed_opens = 0;
597 /* The number of spaces taken up if we print a tab character with width
598 c_ from position h_. */
599 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
601 /* The horizontal position we'll be at after printing a tab character
602 of width c_ from the position h_. */
603 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
605 /* (-NNN) Number of columns of text to print. */
606 static int columns = 1;
608 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
609 first_page_number = 0 will be used to check input only. */
610 static int first_page_number = 0;
611 static int last_page_number = 0;
613 /* Number of files open (not closed, not on hold). */
614 static int files_ready_to_read = 0;
616 /* Current page number. Displayed in header. */
617 static int page_number;
619 /* Current line number. Displayed when -n flag is specified.
621 When printing files in parallel (-m flag), line numbering is as follows:
622 1 foo goo moo
623 2 hoo too zoo
625 When printing files across (-a flag), ...
626 1 foo 2 moo 3 goo
627 4 hoo 5 too 6 zoo
629 Otherwise, line numbering is as follows:
630 1 foo 3 goo 5 too
631 2 moo 4 hoo 6 zoo */
632 static int line_number;
634 /* With line_number overflow, we use power_10 to cut off the higher-order
635 digits of the line_number */
636 static int power_10;
638 /* (-n) True means lines should be preceded by numbers. */
639 static int numbered_lines = FALSE;
641 /* (-n) Character which follows each line number. */
642 static char number_separator = '\t';
644 /* (-n) line counting starts with 1st line of input file (not with 1st
645 line of 1st page printed). */
646 static int line_count = 1;
648 /* (-n) True means counting of skipped lines starts with 1st line of
649 input file. False means -N option is used in addition, counting of
650 skipped lines not required. */
651 static int skip_count = TRUE;
653 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
654 first page printed, usually not 1st page of input file. */
655 static int start_line_num = 1;
657 /* (-n) Width in characters of a line number. */
658 static int chars_per_number = 5;
660 /* Used when widening the first column to accommodate numbers -- only
661 needed when printing files in parallel. Includes width of both the
662 number and the number_separator. */
663 static int number_width;
665 /* Buffer sprintf uses to format a line number. */
666 static char *number_buff;
668 /* (-v) True means unprintable characters are printed as escape sequences.
669 control-g becomes \007. */
670 static int use_esc_sequence = FALSE;
672 /* (-c) True means unprintable characters are printed as control prefixes.
673 control-g becomes ^G. */
674 static int use_cntrl_prefix = FALSE;
676 /* (-d) True means output is double spaced. */
677 static int double_space = FALSE;
679 /* Number of files opened initially in init_files. Should be 1
680 unless we're printing multiple files in parallel. */
681 static int total_files = 0;
683 /* (-r) True means don't complain if we can't open a file. */
684 static int ignore_failed_opens = FALSE;
686 /* (-S) True means we separate columns with a specified string.
687 -S option does not affect line truncation nor column alignment. */
688 static int use_col_separator = FALSE;
690 /* String used to separate columns if the -S option has been specified.
691 Default without -S but together with one of the column options
692 -a|COLUMN|-m is a `space' and with the -J option a `tab'. */
693 static char *col_sep_string = "";
694 static int col_sep_length = 0;
695 static char *column_separator = " ";
696 static char *line_separator = "\t";
698 /* Number of separator characters waiting to be printed as soon as we
699 know that we have any input remaining to be printed. */
700 static int separators_not_printed;
702 /* Position we need to pad to, as soon as we know that we have input
703 remaining to be printed. */
704 static int padding_not_printed;
706 /* True means we should pad the end of the page. Remains false until we
707 know we have a page to print. */
708 static int pad_vertically;
710 /* (-h) String of characters used in place of the filename in the header. */
711 static char *custom_header;
713 /* String containing the date, filename or custom header, and "Page ". */
714 static char *header;
716 static int *clump_buff;
718 /* True means we read the line no. lines_per_body in skip_read
719 called by skip_to_page. That variable controls the coincidence of a
720 "FF set by hand" and "full_page_printed", see above the definition of
721 structure COLUMN. */
722 static int last_line = FALSE;
724 /* If nonzero, print a non-variable date and time with the header
725 -h HEADER using pr test-suite */
726 static int test_suite;
728 static struct option const long_options[] =
730 {"test", no_argument, &test_suite, 1},
731 {"pages", required_argument, NULL, CHAR_MAX + 1},
732 {"columns", required_argument, NULL, CHAR_MAX + 2},
733 {"across", no_argument, NULL, 'a'},
734 {"show-control-chars", no_argument, NULL, 'c'},
735 {"double-space", no_argument, NULL, 'd'},
736 {"expand-tabs", optional_argument, NULL, 'e'},
737 {"form-feed", no_argument, NULL, 'f'},
738 {"header", required_argument, NULL, 'h'},
739 {"output-tabs", optional_argument, NULL, 'i'},
740 {"join-lines", no_argument, NULL, 'J'},
741 {"length", required_argument, NULL, 'l'},
742 {"merge", no_argument, NULL, 'm'},
743 {"number-lines", optional_argument, NULL, 'n'},
744 {"first-line-number", required_argument, NULL, 'N'},
745 {"indent", required_argument, NULL, 'o'},
746 {"no-file-warnings", no_argument, NULL, 'r'},
747 {"separator", optional_argument, NULL, 's'},
748 {"sep-string", optional_argument, NULL, 'S'},
749 {"omit-header", no_argument, NULL, 't'},
750 {"omit-pagination", no_argument, NULL, 'T'},
751 {"show-nonprinting", no_argument, NULL, 'v'},
752 {"width", required_argument, NULL, 'w'},
753 {"page-width", required_argument, NULL, 'W'},
754 {GETOPT_HELP_OPTION_DECL},
755 {GETOPT_VERSION_OPTION_DECL},
756 {0, 0, 0, 0}
759 /* Return the number of columns that have either an open file or
760 stored lines. */
762 static int
763 cols_ready_to_print (void)
765 COLUMN *q;
766 int i;
767 int n;
769 n = 0;
770 for (q = column_vector, i = 0; i < columns; ++q, ++i)
771 if (q->status == OPEN ||
772 q->status == FF_FOUND || /* With -b: To print a header only */
773 (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
774 ++n;
775 return n;
778 /* Estimate first_ / last_page_number
779 using option +FIRST_PAGE:LAST_PAGE */
781 static void
782 first_last_page (char *pages)
784 char *str1;
786 if (*pages == ':')
788 error (0, 0, _("`--pages' invalid range of page numbers: `%s'"), pages);
789 usage (2);
792 str1 = strchr (pages, ':');
793 if (str1 != NULL)
794 *str1 = '\0';
797 long int tmp_long;
798 if (xstrtol (pages, NULL, 10, &tmp_long, "") != LONGINT_OK
799 || tmp_long < 1 || tmp_long > INT_MAX)
800 error (EXIT_FAILURE, 0, _("`--pages' invalid starting page number: `%s'"),
801 pages);
802 first_page_number = (int) tmp_long;
805 if (str1 == NULL)
806 return;
809 long int tmp_long;
810 if (xstrtol (str1 + 1, NULL, 10, &tmp_long, "") != LONGINT_OK
811 || tmp_long <= 0 || tmp_long > INT_MAX)
812 error (EXIT_FAILURE, 0, _("`--pages' invalid ending page number: `%s'"),
813 str1 + 1);
814 last_page_number = (int) tmp_long;
817 if (first_page_number > last_page_number)
818 error (EXIT_FAILURE, 0,
819 _("`--pages' starting page number is larger than ending page number"));
822 /* Estimate length of col_sep_string with option -S[STRING] */
824 static void
825 separator_string (const char *optarg_S)
827 col_sep_length = (int) strlen (optarg_S);
828 col_sep_string = (char *) xmalloc (col_sep_length + 1);
829 strcpy (col_sep_string, optarg_S);
833 main (int argc, char **argv)
835 int c;
836 int accum = 0;
837 int n_files;
838 int old_options = FALSE;
839 int old_w = FALSE;
840 int old_s = FALSE;
841 char **file_names;
843 program_name = argv[0];
844 setlocale (LC_ALL, "");
845 bindtextdomain (PACKAGE, LOCALEDIR);
846 textdomain (PACKAGE);
848 n_files = 0;
849 file_names = (argc > 1
850 ? (char **) xmalloc ((argc - 1) * sizeof (char *))
851 : NULL);
853 while (1)
855 c = getopt_long (argc, argv,
856 "-0123456789abcde::fFh:i::Jl:mn::N:o:rs::S::tTvw:W:",
857 long_options, NULL);
858 if (c == 1) /* Non-option argument. */
860 char *s;
861 s = optarg;
862 if (*s == '+')
864 /* long option --page dominates old `+FIRST_PAGE ...' */
865 if (first_page_number > 0 || last_page_number > 0)
866 continue;
867 ++s;
868 first_last_page (s);
870 else
872 file_names[n_files++] = optarg;
875 else
877 if (ISDIGIT (c))
879 accum = accum * 10 + c - '0';
880 continue;
882 else
884 if (accum > 0)
886 columns = accum;
887 explicit_columns = TRUE;
888 accum = 0;
893 if (c == 1)
894 continue;
896 if (c == EOF)
897 break;
899 switch (c)
901 case 0: /* getopt long option */
902 break;
904 case CHAR_MAX + 1: /* --pages=FIRST_PAGE[:LAST_PAGE] */
905 { /* dominates old opt +... */
906 if (optarg)
907 first_last_page (optarg);
908 else
909 error (EXIT_FAILURE, 0,
910 _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
911 break;
914 case CHAR_MAX + 2: /* --columns=COLUMN */
916 long int tmp_long;
917 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
918 || tmp_long <= 0 || tmp_long > INT_MAX)
920 error (EXIT_FAILURE, 0,
921 _("`--columns=COLUMN' invalid number of columns: `%s'"),
922 optarg);
924 columns = (int) tmp_long;
925 break;
928 case 'a':
929 print_across_flag = TRUE;
930 storing_columns = FALSE;
931 break;
932 case 'b':
933 balance_columns = TRUE;
934 break;
935 case 'c':
936 use_cntrl_prefix = TRUE;
937 break;
938 case 'd':
939 double_space = TRUE;
940 break;
941 case 'e':
942 if (optarg)
943 getoptarg (optarg, 'e', &input_tab_char,
944 &chars_per_input_tab);
945 /* Could check tab width > 0. */
946 untabify_input = TRUE;
947 break;
948 case 'f':
949 case 'F':
950 use_form_feed = TRUE;
951 break;
952 case 'h':
953 custom_header = optarg;
954 standard_header = FALSE;
955 break;
956 case 'i':
957 if (optarg)
958 getoptarg (optarg, 'i', &output_tab_char,
959 &chars_per_output_tab);
960 /* Could check tab width > 0. */
961 tabify_output = TRUE;
962 break;
963 case 'J':
964 join_lines = TRUE;
965 break;
966 case 'l':
968 long int tmp_long;
969 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
970 || tmp_long <= 0 || tmp_long > INT_MAX)
972 error (EXIT_FAILURE, 0,
973 _("`-l PAGE_LENGTH' invalid number of lines: `%s'"),
974 optarg);
976 lines_per_page = (int) tmp_long;
977 break;
979 case 'm':
980 parallel_files = TRUE;
981 storing_columns = FALSE;
982 break;
983 case 'n':
984 numbered_lines = TRUE;
985 if (optarg)
986 getoptarg (optarg, 'n', &number_separator,
987 &chars_per_number);
988 break;
989 case 'N':
990 skip_count = FALSE;
992 long int tmp_long;
993 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
994 || tmp_long > INT_MAX)
996 error (EXIT_FAILURE, 0,
997 _("`-N NUMBER' invalid starting line number: `%s'"),
998 optarg);
1000 start_line_num = (int) tmp_long;
1001 break;
1003 case 'o':
1005 long int tmp_long;
1006 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1007 || tmp_long < 0 || tmp_long > INT_MAX)
1008 error (EXIT_FAILURE, 0,
1009 _("`-o MARGIN' invalid line offset: `%s'"), optarg);
1010 chars_per_margin = (int) tmp_long;
1011 break;
1013 case 'r':
1014 ignore_failed_opens = TRUE;
1015 break;
1016 case 's':
1017 old_options = TRUE;
1018 old_s = TRUE;
1019 if (!use_col_separator && optarg)
1020 separator_string (optarg);
1021 break;
1022 case 'S':
1023 old_s = FALSE;
1024 /* Reset an additional input of -s, -S dominates -s */
1025 col_sep_string = "";
1026 col_sep_length = 0;
1027 use_col_separator = TRUE;
1028 if (optarg)
1029 separator_string (optarg);
1030 break;
1031 case 't':
1032 extremities = FALSE;
1033 keep_FF = TRUE;
1034 break;
1035 case 'T':
1036 extremities = FALSE;
1037 keep_FF = FALSE;
1038 break;
1039 case 'v':
1040 use_esc_sequence = TRUE;
1041 break;
1042 case 'w':
1043 old_options = TRUE;
1044 old_w = TRUE;
1046 long int tmp_long;
1047 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1048 || tmp_long <= 0 || tmp_long > INT_MAX)
1049 error (EXIT_FAILURE, 0,
1050 _("`-w PAGE_WIDTH' invalid number of characters: `%s'"), optarg);
1051 if (!truncate_lines) chars_per_line = (int) tmp_long;
1052 break;
1054 case 'W':
1055 old_w = FALSE; /* dominates -w */
1056 truncate_lines = TRUE;
1058 long int tmp_long;
1059 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1060 || tmp_long <= 0 || tmp_long > INT_MAX)
1061 error (EXIT_FAILURE, 0,
1062 _("`-W PAGE_WIDTH' invalid number of characters: `%s'"), optarg);
1063 chars_per_line = (int) tmp_long;
1064 break;
1066 case_GETOPT_HELP_CHAR;
1067 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1068 default:
1069 usage (2);
1070 break;
1074 /* Now we can set a reasonable initial value: */
1075 if (first_page_number == 0)
1076 first_page_number = 1;
1078 if (parallel_files && explicit_columns)
1079 error (EXIT_FAILURE, 0,
1080 _("Cannot specify number of columns when printing in parallel."));
1082 if (parallel_files && print_across_flag)
1083 error (EXIT_FAILURE, 0,
1084 _("Cannot specify both printing across and printing in parallel."));
1086 /* Translate some old short options to new/long options.
1087 To meet downward compatibility with other UNIX pr utilities
1088 and some POSIX specifications. */
1090 if (old_options)
1092 if (old_w)
1094 if (parallel_files || explicit_columns)
1096 /* activate -W */
1097 truncate_lines = TRUE;
1098 if (old_s)
1099 /* adapt HP-UX and SunOS: -s = no separator;
1100 activate -S */
1101 use_col_separator = TRUE;
1103 else
1104 /* old -w sets width with columns only
1105 activate -J */
1106 join_lines = TRUE;
1108 else if (!use_col_separator)
1110 /* No -S option read */
1111 if (old_s && (parallel_files || explicit_columns))
1113 if (!truncate_lines)
1115 /* old -s (without -w and -W) annuls column alignment,
1116 uses fields, activate -J */
1117 join_lines = TRUE;
1118 if (col_sep_length > 0)
1119 /* activate -S */
1120 use_col_separator = TRUE;
1122 else
1123 /* with -W */
1124 /* adapt HP-UX and SunOS: -s = no separator;
1125 activate -S */
1126 use_col_separator = TRUE;
1131 for (; optind < argc; optind++)
1133 file_names[n_files++] = argv[optind];
1136 if (n_files == 0)
1138 /* No file arguments specified; read from standard input. */
1139 print_files (0, NULL);
1141 else
1143 if (parallel_files)
1144 print_files (n_files, file_names);
1145 else
1147 int i;
1148 for (i = 0; i < n_files; i++)
1149 print_files (1, &file_names[i]);
1153 cleanup ();
1155 if (have_read_stdin && fclose (stdin) == EOF)
1156 error (EXIT_FAILURE, errno, _("standard input"));
1157 if (ferror (stdout) || fclose (stdout) == EOF)
1158 error (EXIT_FAILURE, errno, _("write error"));
1159 if (failed_opens > 0)
1160 exit (EXIT_FAILURE);
1161 exit (EXIT_SUCCESS);
1164 /* Parse options of the form -scNNN.
1166 Example: -nck, where 'n' is the option, c is the optional number
1167 separator, and k is the optional width of the field used when printing
1168 a number. */
1170 static void
1171 getoptarg (char *arg, char switch_char, char *character, int *number)
1173 if (!ISDIGIT (*arg))
1174 *character = *arg++;
1175 if (*arg)
1177 long int tmp_long;
1178 if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK
1179 || tmp_long <= 0 || tmp_long > INT_MAX)
1181 error (0, 0,
1182 _("`-%c' extra characters or invalid number in the argument: `%s'"),
1183 switch_char, arg);
1184 usage (2);
1186 *number = (int) tmp_long;
1190 /* Set parameters related to formatting. */
1192 static void
1193 init_parameters (int number_of_files)
1195 int chars_used_by_number = 0;
1197 if (use_form_feed)
1199 lines_per_header = 3;
1200 lines_per_footer = 0;
1203 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1204 if (lines_per_body <= 0)
1206 extremities = FALSE;
1207 keep_FF = TRUE;
1209 if (extremities == FALSE)
1210 lines_per_body = lines_per_page;
1212 if (double_space)
1213 lines_per_body = lines_per_body / 2;
1215 /* If input is stdin, cannot print parallel files. BSD dumps core
1216 on this. */
1217 if (number_of_files == 0)
1218 parallel_files = FALSE;
1220 if (parallel_files)
1221 columns = number_of_files;
1223 /* One file, multi columns down: -b option is set to get a consistent
1224 formulation with "FF set by hand" in input files. */
1225 if (storing_columns)
1226 balance_columns = TRUE;
1228 /* Tabification is assumed for multiple columns. */
1229 if (columns > 1)
1231 if (!use_col_separator)
1233 /* Use default separator */
1234 if (join_lines)
1235 col_sep_string = line_separator;
1236 else
1237 col_sep_string = column_separator;
1239 col_sep_length = 1;
1240 use_col_separator = TRUE;
1242 /* It's rather pointless to define a TAB separator with column
1243 alignment */
1244 else if (!join_lines && *col_sep_string == '\t')
1245 col_sep_string = column_separator;
1247 truncate_lines = TRUE;
1248 untabify_input = TRUE;
1249 tabify_output = TRUE;
1251 else
1252 storing_columns = FALSE;
1254 /* -J dominates -w in any case */
1255 if (join_lines)
1256 truncate_lines = FALSE;
1258 if (numbered_lines)
1260 int tmp_i;
1261 int chars_per_default_tab = 8;
1263 line_count = start_line_num;
1265 /* To allow input tab-expansion (-e sensitive) use:
1266 if (number_separator == input_tab_char)
1267 number_width = chars_per_number +
1268 TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1270 /* Estimate chars_per_text without any margin and keep it constant. */
1271 if (number_separator == '\t')
1272 number_width = chars_per_number +
1273 TAB_WIDTH (chars_per_default_tab, chars_per_number);
1274 else
1275 number_width = chars_per_number + 1;
1277 /* The number is part of the column width unless we are
1278 printing files in parallel. */
1279 if (parallel_files)
1280 chars_used_by_number = number_width;
1282 /* We use power_10 to cut off the higher-order digits of the
1283 line_number in function add_line_number */
1284 tmp_i = chars_per_number;
1285 for (power_10 = 1; tmp_i > 0; --tmp_i)
1286 power_10 = 10 * power_10;
1289 chars_per_column = (chars_per_line - chars_used_by_number -
1290 (columns - 1) * col_sep_length) / columns;
1292 if (chars_per_column < 1)
1293 error (EXIT_FAILURE, 0, _("page width too narrow"));
1295 if (numbered_lines)
1297 if (number_buff != NULL)
1298 free (number_buff);
1299 number_buff = (char *) xmalloc (2 * chars_per_number);
1302 /* Pick the maximum between the tab width and the width of an
1303 escape sequence.
1304 The width of an escape sequence (4) isn't the lower limit any longer.
1305 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1306 to expand a tab which is not an input_tab-char. */
1307 if (clump_buff != NULL)
1308 free (clump_buff);
1309 clump_buff = (int *) xmalloc ((chars_per_input_tab > 8
1310 ? chars_per_input_tab : 8) * sizeof (int));
1313 /* Open the necessary files,
1314 maintaining a COLUMN structure for each column.
1316 With multiple files, each column p has a different p->fp.
1317 With single files, each column p has the same p->fp.
1318 Return 1 if (number_of_files > 0) and no files can be opened,
1319 0 otherwise.
1321 With each column/file p, p->full_page_printed is initialized,
1322 see also open_file. */
1324 static int
1325 init_fps (int number_of_files, char **av)
1327 int i, files_left;
1328 COLUMN *p;
1329 FILE *firstfp;
1330 char *firstname;
1332 total_files = 0;
1334 if (column_vector != NULLCOL)
1335 free ((char *) column_vector);
1336 column_vector = (COLUMN *) xmalloc (columns * sizeof (COLUMN));
1338 if (parallel_files)
1340 files_left = number_of_files;
1341 for (p = column_vector; files_left--; ++p, ++av)
1343 if (open_file (*av, p) == 0)
1345 --p;
1346 --columns;
1349 if (columns == 0)
1350 return 1;
1351 init_header ("", -1);
1353 else
1355 p = column_vector;
1356 if (number_of_files > 0)
1358 if (open_file (*av, p) == 0)
1359 return 1;
1360 init_header (*av, fileno (p->fp));
1361 p->lines_stored = 0;
1363 else
1365 p->name = _("standard input");
1366 p->fp = stdin;
1367 have_read_stdin = TRUE;
1368 p->status = OPEN;
1369 p->full_page_printed = FALSE;
1370 ++total_files;
1371 init_header ("", -1);
1372 p->lines_stored = 0;
1375 firstname = p->name;
1376 firstfp = p->fp;
1377 for (i = columns - 1, ++p; i; --i, ++p)
1379 p->name = firstname;
1380 p->fp = firstfp;
1381 p->status = OPEN;
1382 p->full_page_printed = FALSE;
1383 p->lines_stored = 0;
1386 files_ready_to_read = total_files;
1387 return 0;
1390 /* Determine print_func and char_func, the functions
1391 used by each column for printing and/or storing.
1393 Determine the horizontal position desired when we begin
1394 printing a column (p->start_position). */
1396 static void
1397 init_funcs (void)
1399 int i, h, h_next;
1400 COLUMN *p;
1402 h = chars_per_margin;
1404 if (!truncate_lines)
1405 h_next = ANYWHERE;
1406 else
1408 /* When numbering lines of parallel files, we enlarge the
1409 first column to accomodate the number. Looks better than
1410 the Sys V approach. */
1411 if (parallel_files && numbered_lines)
1412 h_next = h + chars_per_column + number_width;
1413 else
1414 h_next = h + chars_per_column;
1417 /* Enlarge p->start_position of first column to use the same form of
1418 padding_not_printed with all columns. */
1419 h = h + col_sep_length;
1421 /* This loop takes care of all but the rightmost column. */
1423 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1425 if (storing_columns) /* One file, multi columns down. */
1427 p->char_func = store_char;
1428 p->print_func = print_stored;
1430 else
1431 /* One file, multi columns across; or parallel files. */
1433 p->char_func = print_char;
1434 p->print_func = read_line;
1437 /* Number only the first column when printing files in
1438 parallel. */
1439 p->numbered = numbered_lines && (!parallel_files || i == 1);
1440 p->start_position = h;
1442 /* If we don't truncate lines, all start_positions are
1443 ANYWHERE, except the first column's start_position when
1444 using a margin. */
1446 if (!truncate_lines)
1448 h = ANYWHERE;
1449 h_next = ANYWHERE;
1451 else
1453 h = h_next + col_sep_length;
1454 h_next = h + chars_per_column;
1458 /* The rightmost column.
1460 Doesn't need to be stored unless we intend to balance
1461 columns on the last page. */
1462 if (storing_columns && balance_columns)
1464 p->char_func = store_char;
1465 p->print_func = print_stored;
1467 else
1469 p->char_func = print_char;
1470 p->print_func = read_line;
1473 p->numbered = numbered_lines && (!parallel_files || i == 1);
1474 p->start_position = h;
1477 /* Open a file. Return nonzero if successful, zero if failed.
1479 With each file p, p->full_page_printed is initialized,
1480 see also init_fps. */
1482 static int
1483 open_file (char *name, COLUMN *p)
1485 if (STREQ (name, "-"))
1487 p->name = _("standard input");
1488 p->fp = stdin;
1489 have_read_stdin = 1;
1491 else
1493 p->name = name;
1494 p->fp = fopen (name, "r");
1496 if (p->fp == NULL)
1498 ++failed_opens;
1499 if (!ignore_failed_opens)
1500 error (0, errno, "%s", name);
1501 return 0;
1503 p->status = OPEN;
1504 p->full_page_printed = FALSE;
1505 ++total_files;
1506 return 1;
1509 /* Close the file in P.
1511 If we aren't dealing with multiple files in parallel, we change
1512 the status of all columns in the column list to reflect the close. */
1514 static void
1515 close_file (COLUMN *p)
1517 COLUMN *q;
1518 int i;
1520 if (p->status == CLOSED)
1521 return;
1522 if (ferror (p->fp))
1523 error (EXIT_FAILURE, errno, "%s", p->name);
1524 if (p->fp != stdin && fclose (p->fp) == EOF)
1525 error (EXIT_FAILURE, errno, "%s", p->name);
1527 if (!parallel_files)
1529 for (q = column_vector, i = columns; i; ++q, --i)
1531 q->status = CLOSED;
1532 if (q->lines_stored == 0)
1534 q->lines_to_print = 0;
1538 else
1540 p->status = CLOSED;
1541 p->lines_to_print = 0;
1544 --files_ready_to_read;
1547 /* Put a file on hold until we start a new page,
1548 since we've hit a form feed.
1550 If we aren't dealing with parallel files, we must change the
1551 status of all columns in the column list. */
1553 static void
1554 hold_file (COLUMN *p)
1556 COLUMN *q;
1557 int i;
1559 if (!parallel_files)
1560 for (q = column_vector, i = columns; i; ++q, --i)
1562 if (storing_columns)
1563 q->status = FF_FOUND;
1564 else
1565 q->status = ON_HOLD;
1567 else
1568 p->status = ON_HOLD;
1570 p->lines_to_print = 0;
1571 --files_ready_to_read;
1574 /* Undo hold_file -- go through the column list and change any
1575 ON_HOLD columns to OPEN. Used at the end of each page. */
1577 static void
1578 reset_status (void)
1580 int i = columns;
1581 COLUMN *p;
1583 for (p = column_vector; i; --i, ++p)
1584 if (p->status == ON_HOLD)
1586 p->status = OPEN;
1587 files_ready_to_read++;
1590 if (storing_columns)
1592 if (column_vector->status == CLOSED)
1593 /* We use the info to output an error message in skip_to_page. */
1594 files_ready_to_read = 0;
1595 else
1596 files_ready_to_read = 1;
1600 /* Print a single file, or multiple files in parallel.
1602 Set up the list of columns, opening the necessary files.
1603 Allocate space for storing columns, if necessary.
1604 Skip to first_page_number, if user has asked to skip leading pages.
1605 Determine which functions are appropriate to store/print lines
1606 in each column.
1607 Print the file(s). */
1609 static void
1610 print_files (int number_of_files, char **av)
1612 init_parameters (number_of_files);
1613 if (init_fps (number_of_files, av))
1614 return;
1615 if (storing_columns)
1616 init_store_cols ();
1618 if (first_page_number > 1)
1620 if (!skip_to_page (first_page_number))
1621 return;
1622 else
1623 page_number = first_page_number;
1625 else
1626 page_number = 1;
1628 init_funcs ();
1630 line_number = line_count;
1631 while (print_page ())
1635 /* Estimate the number of characters taken up by a short format date and
1636 time: "yy-mm-dd HH:MM" and: "Page NNNN". */
1637 #define CHARS_FOR_DATE_AND_PAGE 25
1639 /* Initialize header information.
1640 If DESC is non-negative, it is a file descriptor open to
1641 FILENAME for reading.
1643 Allocate space for a header string,
1644 Determine the time, insert file name or user-specified string.
1645 Make use of a centered header with left-hand-side truncation marked by
1646 a '*` in front, if necessary. */
1648 static void
1649 init_header (char *filename, int desc)
1651 int chars_per_middle, chars_free, lhs_blanks, rhs_blanks;
1652 char *f = filename;
1653 char *no_middle = "";
1654 char *header_text;
1655 struct tm *tmptr;
1656 struct stat st;
1657 char *datim = "-- Date/Time -- ";
1659 if (filename == NULL)
1660 f = "";
1662 if (header != NULL)
1663 free (header);
1664 header = (char *) xmalloc (chars_per_line + 1);
1666 if (!standard_header && *custom_header == '\0')
1667 *header = '\0'; /* blank line header */
1668 else
1670 #define T_BUF_FMT "%Y-%m-%d %H:%M" /* date/time short format */
1671 #define T_BUF_SIZE 17 /* FIXME: using a literal here is fragile. */
1672 char t_buf[T_BUF_SIZE];
1674 /* If parallel files or standard input, use current time. */
1675 if (desc < 0 || STREQ (filename, "-") || fstat (desc, &st))
1676 st.st_mtime = time (NULL);
1678 tmptr = localtime (&st.st_mtime);
1679 strftime (t_buf, T_BUF_SIZE, T_BUF_FMT, tmptr);
1681 chars_per_middle = chars_per_line - CHARS_FOR_DATE_AND_PAGE;
1682 if (chars_per_middle < 3)
1684 header_text = no_middle; /* Nothing free for a heading */
1685 lhs_blanks = 1;
1686 rhs_blanks = 1;
1688 else
1690 header_text = standard_header ? f : custom_header;
1691 chars_free = chars_per_middle - (int) strlen (header_text);
1692 if (chars_free > 1)
1694 lhs_blanks = chars_free / 2; /* text not truncated */
1695 rhs_blanks = chars_free - lhs_blanks;
1697 else
1698 { /* lhs truncation */
1699 header_text = header_text - chars_free + 2;
1700 *header_text = '*';
1701 lhs_blanks = 1;
1702 rhs_blanks = 1;
1706 sprintf (header, _("%s%*s%s%*sPage"), (test_suite ? datim : t_buf),
1707 lhs_blanks, " ", header_text, rhs_blanks, " ");
1711 /* Set things up for printing a page
1713 Scan through the columns ...
1714 Determine which are ready to print
1715 (i.e., which have lines stored or open files)
1716 Set p->lines_to_print appropriately
1717 (to p->lines_stored if we're storing, or lines_per_body
1718 if we're reading straight from the file)
1719 Keep track of this total so we know when to stop printing */
1721 static void
1722 init_page (void)
1724 int j;
1725 COLUMN *p;
1727 if (storing_columns)
1729 store_columns ();
1730 for (j = columns - 1, p = column_vector; j; --j, ++p)
1732 p->lines_to_print = p->lines_stored;
1735 /* Last column. */
1736 if (balance_columns)
1738 p->lines_to_print = p->lines_stored;
1740 /* Since we're not balancing columns, we don't need to store
1741 the rightmost column. Read it straight from the file. */
1742 else
1744 if (p->status == OPEN)
1746 p->lines_to_print = lines_per_body;
1748 else
1749 p->lines_to_print = 0;
1752 else
1753 for (j = columns, p = column_vector; j; --j, ++p)
1754 if (p->status == OPEN)
1756 p->lines_to_print = lines_per_body;
1758 else
1759 p->lines_to_print = 0;
1762 /* Align empty columns and print separators.
1763 Empty columns will be formed by files with status ON_HOLD or CLOSED
1764 when printing multiple files in parallel. */
1766 static void
1767 align_column (COLUMN *p)
1769 padding_not_printed = p->start_position;
1770 if (padding_not_printed - col_sep_length > 0)
1772 pad_across_to (padding_not_printed - col_sep_length);
1773 padding_not_printed = ANYWHERE;
1776 if (use_col_separator)
1777 print_sep_string ();
1779 if (p->numbered)
1780 add_line_number (p);
1783 /* Print one page.
1785 As long as there are lines left on the page and columns ready to print,
1786 Scan across the column list
1787 if the column has stored lines or the file is open
1788 pad to the appropriate spot
1789 print the column
1790 pad the remainder of the page with \n or \f as requested
1791 reset the status of all files -- any files which where on hold because
1792 of formfeeds are now put back into the lineup. */
1794 static int
1795 print_page (void)
1797 int j;
1798 int lines_left_on_page;
1799 COLUMN *p;
1801 /* Used as an accumulator (with | operator) of successive values of
1802 pad_vertically. The trick is to set pad_vertically
1803 to zero before each run through the inner loop, then after that
1804 loop, it tells us whether a line was actually printed (whether a
1805 newline needs to be output -- or two for double spacing). But those
1806 values have to be accumulated (in pv) so we can invoke pad_down
1807 properly after the outer loop completes. */
1808 int pv;
1810 init_page ();
1812 if (cols_ready_to_print () == 0)
1813 return FALSE;
1815 if (extremities)
1816 print_a_header = TRUE;
1818 /* Don't pad unless we know a page was printed. */
1819 pad_vertically = FALSE;
1820 pv = FALSE;
1822 lines_left_on_page = lines_per_body;
1823 if (double_space)
1824 lines_left_on_page *= 2;
1826 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1828 output_position = 0;
1829 spaces_not_printed = 0;
1830 separators_not_printed = 0;
1831 pad_vertically = FALSE;
1832 align_empty_cols = FALSE;
1833 empty_line = TRUE;
1835 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1837 input_position = 0;
1838 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1840 FF_only = FALSE;
1841 padding_not_printed = p->start_position;
1842 if (!(p->print_func) (p))
1843 read_rest_of_line (p);
1844 pv |= pad_vertically;
1846 --p->lines_to_print;
1847 if (p->lines_to_print <= 0)
1849 if (cols_ready_to_print () <= 0)
1850 break;
1853 /* File p changed its status to ON_HOLD or CLOSED */
1854 if (parallel_files && p->status != OPEN)
1856 if (empty_line)
1857 align_empty_cols = TRUE;
1858 else if (p->status == CLOSED ||
1859 (p->status == ON_HOLD && FF_only))
1860 align_column (p);
1863 else if (parallel_files)
1865 /* File status ON_HOLD or CLOSED */
1866 if (empty_line)
1867 align_empty_cols = TRUE;
1868 else
1869 align_column (p);
1872 /* We need it also with an empty column */
1873 if (use_col_separator)
1874 ++separators_not_printed;
1877 if (pad_vertically)
1879 putchar ('\n');
1880 --lines_left_on_page;
1883 if (cols_ready_to_print () <= 0 && !extremities)
1884 break;
1886 if (double_space && pv)
1888 putchar ('\n');
1889 --lines_left_on_page;
1893 if (lines_left_on_page == 0)
1894 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1895 if (p->status == OPEN)
1896 p->full_page_printed = TRUE;
1898 pad_vertically = pv;
1900 if (pad_vertically && extremities)
1901 pad_down (lines_left_on_page + lines_per_footer);
1902 else if (keep_FF && print_a_FF)
1904 putchar ('\f');
1905 print_a_FF = FALSE;
1908 if (last_page_number && page_number > last_page_number)
1909 return FALSE; /* Stop printing with LAST_PAGE */
1911 reset_status (); /* Change ON_HOLD to OPEN. */
1913 return TRUE; /* More pages to go. */
1916 /* Allocate space for storing columns.
1918 This is necessary when printing multiple columns from a single file.
1919 Lines are stored consecutively in buff, separated by '\0'.
1921 The following doesn't apply any longer - any tuning possible?
1922 (We can't use a fixed offset since with the '-s' flag lines aren't
1923 truncated.)
1925 We maintain a list (line_vector) of pointers to the beginnings
1926 of lines in buff. We allocate one more than the number of lines
1927 because the last entry tells us the index of the last character,
1928 which we need to know in order to print the last line in buff. */
1930 static void
1931 init_store_cols (void)
1933 int total_lines = lines_per_body * columns;
1934 int chars_if_truncate = total_lines * (chars_per_column + 1);
1936 if (line_vector != NULL)
1937 free ((int *) line_vector);
1938 /* FIXME: here's where it was allocated. */
1939 line_vector = (int *) xmalloc ((total_lines + 1) * sizeof (int *));
1941 if (end_vector != NULL)
1942 free ((int *) end_vector);
1943 end_vector = (int *) xmalloc (total_lines * sizeof (int *));
1945 if (buff != NULL)
1946 free (buff);
1947 buff_allocated = (use_col_separator
1948 ? 2 * chars_if_truncate
1949 : chars_if_truncate); /* Tune this. */
1950 buff = (char *) xmalloc (buff_allocated);
1953 /* Store all but the rightmost column.
1954 (Used when printing a single file in multiple downward columns)
1956 For each column
1957 set p->current_line to be the index in line_vector of the
1958 first line in the column
1959 For each line in the column
1960 store the line in buff
1961 add to line_vector the index of the line's first char
1962 buff_start is the index in buff of the first character in the
1963 current line. */
1965 static void
1966 store_columns (void)
1968 int i, j;
1969 int line = 0;
1970 int buff_start;
1971 int last_col; /* The rightmost column which will be saved in buff */
1972 COLUMN *p;
1974 buff_current = 0;
1975 buff_start = 0;
1977 if (balance_columns)
1978 last_col = columns;
1979 else
1980 last_col = columns - 1;
1982 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1983 p->lines_stored = 0;
1985 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1986 ++i, ++p)
1988 p->current_line = line;
1989 for (j = lines_per_body; j && files_ready_to_read; --j)
1991 if (p->status == OPEN) /* Redundant. Clean up. */
1993 input_position = 0;
1995 if (!read_line (p))
1996 read_rest_of_line (p);
1998 if (p->status == OPEN
1999 || buff_start != buff_current)
2001 ++p->lines_stored;
2002 line_vector[line] = buff_start;
2003 end_vector[line++] = input_position;
2004 buff_start = buff_current;
2009 /* Keep track of the location of the last char in buff. */
2010 line_vector[line] = buff_start;
2012 if (balance_columns && p->lines_stored != lines_per_body)
2013 balance (line);
2016 static void
2017 balance (int total_stored)
2019 COLUMN *p;
2020 int i, lines;
2021 int first_line = 0;
2023 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
2025 lines = total_stored / columns;
2026 if (i <= total_stored % columns)
2027 ++lines;
2029 p->lines_stored = lines;
2030 p->current_line = first_line;
2032 first_line += lines;
2036 /* Store a character in the buffer. */
2038 static void
2039 store_char (int c)
2041 if (buff_current >= buff_allocated)
2043 /* May be too generous. */
2044 buff_allocated = 2 * buff_allocated;
2045 buff = (char *) xrealloc (buff, buff_allocated * sizeof (char));
2047 buff[buff_current++] = (char) c;
2050 static void
2051 add_line_number (COLUMN *p)
2053 int i;
2054 char *s;
2055 int left_cut;
2057 /* Cutting off the higher-order digits is more informative than
2058 lower-order cut off*/
2059 if (line_number < power_10)
2060 sprintf (number_buff, "%*d", chars_per_number, line_number);
2061 else
2063 left_cut = line_number % power_10;
2064 sprintf (number_buff, "%0*d", chars_per_number, left_cut);
2066 line_number++;
2067 s = number_buff;
2068 for (i = chars_per_number; i > 0; i--)
2069 (p->char_func) ((int) *s++);
2071 if (columns > 1)
2073 /* Tabification is assumed for multiple columns, also for n-separators,
2074 but `default n-separator = TAB' hasn't been given priority over
2075 equal column_width also specified by POSIX. */
2076 if (number_separator == '\t')
2078 i = number_width - chars_per_number;
2079 while (i-- > 0)
2080 (p->char_func) ((int) ' ');
2082 else
2083 (p->char_func) ((int) number_separator);
2085 else
2086 /* To comply with POSIX, we avoid any expansion of default TAB
2087 separator with a single column output. No column_width requirement
2088 has to be considered. */
2090 (p->char_func) ((int) number_separator);
2091 if (number_separator == '\t')
2092 output_position = POS_AFTER_TAB (chars_per_output_tab,
2093 output_position);
2096 if (truncate_lines && !parallel_files)
2097 input_position += number_width;
2100 /* Print (or store) padding until the current horizontal position
2101 is position. */
2103 static void
2104 pad_across_to (int position)
2106 register int h = output_position;
2108 if (tabify_output)
2109 spaces_not_printed = position - output_position;
2110 else
2112 while (++h <= position)
2113 putchar (' ');
2114 output_position = position;
2118 /* Pad to the bottom of the page.
2120 If the user has requested a formfeed, use one.
2121 Otherwise, use newlines. */
2123 static void
2124 pad_down (int lines)
2126 register int i;
2128 if (use_form_feed)
2129 putchar ('\f');
2130 else
2131 for (i = lines; i; --i)
2132 putchar ('\n');
2135 /* Read the rest of the line.
2137 Read from the current column's file until an end of line is
2138 hit. Used when we've truncated a line and we no longer need
2139 to print or store its characters. */
2141 static void
2142 read_rest_of_line (COLUMN *p)
2144 register int c;
2145 FILE *f = p->fp;
2147 while ((c = getc (f)) != '\n')
2149 if (c == '\f')
2151 if ((c = getc (f)) != '\n')
2152 ungetc (c, f);
2153 if (keep_FF)
2154 print_a_FF = TRUE;
2155 hold_file (p);
2156 break;
2158 else if (c == EOF)
2160 close_file (p);
2161 break;
2166 /* Read a line with skip_to_page.
2168 Read from the current column's file until an end of line is
2169 hit. Used when we read full lines to skip pages.
2170 With skip_to_page we have to check for FF-coincidence which is done
2171 in function read_line otherwise.
2172 Count lines of skipped pages to find the line number of 1st page
2173 printed relative to 1st line of input file (start_line_num). */
2175 static void
2176 skip_read (COLUMN *p, int column_number)
2178 register int c;
2179 FILE *f = p->fp;
2180 int i, single_ff = FALSE;
2181 COLUMN *q;
2183 /* Read 1st character in a line or any character succeeding a FF */
2184 if ((c = getc (f)) == '\f' && p->full_page_printed)
2185 /* A FF-coincidence with a previous full_page_printed.
2186 To avoid an additional empty page, eliminate the FF */
2187 if ((c = getc (f)) == '\n')
2188 c = getc (f);
2190 p->full_page_printed = FALSE;
2192 /* 1st character a FF means a single FF without any printable
2193 characters. Don't count it as a line with -n option. */
2194 if (c == '\f')
2195 single_ff = TRUE;
2197 /* Preparing for a FF-coincidence: Maybe we finish that page
2198 without a FF found */
2199 if (last_line)
2200 p->full_page_printed = TRUE;
2202 while (c != '\n')
2204 if (c == '\f')
2206 /* No FF-coincidence possible,
2207 no catching up of a FF-coincidence with next page */
2208 if (last_line)
2210 if (!parallel_files)
2211 for (q = column_vector, i = columns; i; ++q, --i)
2212 q->full_page_printed = FALSE;
2213 else
2214 p->full_page_printed = FALSE;
2217 if ((c = getc (f)) != '\n')
2218 ungetc (c, f);
2219 hold_file (p);
2220 break;
2222 else if (c == EOF)
2224 close_file (p);
2225 break;
2227 c = getc (f);
2230 if (skip_count)
2231 if ((!parallel_files || column_number == 1) && !single_ff)
2232 ++line_count;
2235 /* If we're tabifying output,
2237 When print_char encounters white space it keeps track
2238 of our desired horizontal position and delays printing
2239 until this function is called. */
2241 static void
2242 print_white_space (void)
2244 register int h_new;
2245 register int h_old = output_position;
2246 register int goal = h_old + spaces_not_printed;
2248 while (goal - h_old > 1
2249 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2251 putchar (output_tab_char);
2252 h_old = h_new;
2254 while (++h_old <= goal)
2255 putchar (' ');
2257 output_position = goal;
2258 spaces_not_printed = 0;
2261 /* Print column separators.
2263 We keep a count until we know that we'll be printing a line,
2264 then print_sep_string() is called. */
2266 static void
2267 print_sep_string ()
2269 char *s;
2270 int l = col_sep_length;
2272 s = col_sep_string;
2274 if (separators_not_printed <= 0)
2276 /* We'll be starting a line with chars_per_margin, anything else? */
2277 if (spaces_not_printed > 0)
2278 print_white_space ();
2280 else
2282 for (; separators_not_printed > 0; --separators_not_printed)
2284 while (l-- > 0)
2286 /* 3 types of sep_strings: spaces only, spaces and chars,
2287 chars only */
2288 if (*s == ' ')
2290 /* We're tabifying output; consecutive spaces in
2291 sep_string may have to be converted to tabs */
2292 s++;
2293 ++spaces_not_printed;
2295 else
2297 if (spaces_not_printed > 0)
2298 print_white_space ();
2299 putchar (*s++);
2300 ++output_position;
2303 /* sep_string ends with some spaces */
2304 if (spaces_not_printed > 0)
2305 print_white_space ();
2310 /* Print (or store, depending on p->char_func) a clump of N
2311 characters. */
2313 static void
2314 print_clump (COLUMN *p, int n, int *clump)
2316 while (n--)
2317 (p->char_func) (*clump++);
2320 /* Print a character.
2322 Update the following comment: process-char hasn't been used any
2323 longer.
2324 If we're tabifying, all tabs have been converted to spaces by
2325 process_char(). Keep a count of consecutive spaces, and when
2326 a nonspace is encountered, call print_white_space() to print the
2327 required number of tabs and spaces. */
2329 static void
2330 print_char (int c)
2332 if (tabify_output)
2334 if (c == ' ')
2336 ++spaces_not_printed;
2337 return;
2339 else if (spaces_not_printed > 0)
2340 print_white_space ();
2342 /* Nonprintables are assumed to have width 0, except '\b'. */
2343 if (!ISPRINT (c))
2345 if (c == '\b')
2346 --output_position;
2348 else
2349 ++output_position;
2351 putchar (c);
2354 /* Skip to page PAGE before printing.
2355 PAGE may be larger than total number of pages. */
2357 static int
2358 skip_to_page (int page)
2360 int n, i, j;
2361 COLUMN *p;
2363 for (n = 1; n < page; ++n)
2365 for (i = 1; i < lines_per_body; ++i)
2367 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2368 if (p->status == OPEN)
2369 skip_read (p, j);
2371 last_line = TRUE;
2372 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2373 if (p->status == OPEN)
2374 skip_read (p, j);
2376 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2377 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2378 if (p->status != CLOSED)
2379 p->status = ON_HOLD;
2381 reset_status ();
2382 last_line = FALSE;
2384 if (files_ready_to_read < 1)
2386 /* It's very helpful, normally the total number of pages is
2387 not known in advance. */
2388 error (0, 0,
2389 _("starting page number larger than total number of pages: `%d'"),
2391 break;
2394 return files_ready_to_read > 0;
2397 /* Print a header.
2399 Formfeeds are assumed to use up two lines at the beginning of
2400 the page. */
2402 static void
2403 print_header (void)
2405 if (!use_form_feed)
2406 fprintf (stdout, "\n\n");
2408 output_position = 0;
2409 pad_across_to (chars_per_margin);
2410 print_white_space ();
2412 if (!standard_header && *custom_header == '\0')
2414 fprintf (stdout, "%s\n\n\n", header);
2415 page_number++;
2417 else
2418 fprintf (stdout, "%s%5d\n\n\n", header, page_number++);
2420 print_a_header = FALSE;
2421 output_position = 0;
2424 /* Print (or store, if p->char_func is store_char()) a line.
2426 Read a character to determine whether we have a line or not.
2427 (We may hit EOF, \n, or \f)
2429 Once we know we have a line,
2430 set pad_vertically = TRUE, meaning it's safe
2431 to pad down at the end of the page, since we do have a page.
2432 print a header if needed.
2433 pad across to padding_not_printed if needed.
2434 print any separators which need to be printed.
2435 print a line number if it needs to be printed.
2437 Print the clump which corresponds to the first character.
2439 Enter a loop and keep printing until an end of line condition
2440 exists, or until we exceed chars_per_column.
2442 Return FALSE if we exceed chars_per_column before reading
2443 an end of line character, TRUE otherwise. */
2445 static int
2446 read_line (COLUMN *p)
2448 register int c, chars;
2449 int last_input_position;
2450 int j, k;
2451 COLUMN *q;
2453 /* Suppress `used before initialized' warning. */
2454 #ifdef lint
2455 chars = 0;
2456 #endif
2458 /* read 1st character in each line or any character succeeding a FF: */
2459 c = getc (p->fp);
2461 last_input_position = input_position;
2463 if (c == '\f' && p->full_page_printed)
2464 if ((c = getc (p->fp)) == '\n')
2465 c = getc (p->fp);
2466 p->full_page_printed = FALSE;
2468 switch (c)
2470 case '\f':
2471 if ((c = getc (p->fp)) != '\n')
2472 ungetc (c, p->fp);
2473 FF_only = TRUE;
2474 if (print_a_header && !storing_columns)
2476 pad_vertically = TRUE;
2477 print_header ();
2479 else if (keep_FF)
2480 print_a_FF = TRUE;
2481 hold_file (p);
2482 return TRUE;
2483 case EOF:
2484 close_file (p);
2485 return TRUE;
2486 case '\n':
2487 break;
2488 default:
2489 chars = char_to_clump (c);
2492 if (truncate_lines && input_position > chars_per_column)
2494 input_position = last_input_position;
2495 return FALSE;
2498 if (p->char_func != store_char)
2500 pad_vertically = TRUE;
2502 if (print_a_header && !storing_columns)
2503 print_header ();
2505 if (parallel_files && align_empty_cols)
2507 /* We have to align empty columns at the beginning of a line. */
2508 k = separators_not_printed;
2509 separators_not_printed = 0;
2510 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2512 align_column (q);
2513 separators_not_printed += 1;
2515 padding_not_printed = p->start_position;
2516 if (truncate_lines)
2517 spaces_not_printed = chars_per_column;
2518 else
2519 spaces_not_printed = 0;
2520 align_empty_cols = FALSE;
2523 if (padding_not_printed - col_sep_length > 0)
2525 pad_across_to (padding_not_printed - col_sep_length);
2526 padding_not_printed = ANYWHERE;
2529 if (use_col_separator)
2530 print_sep_string ();
2533 if (p->numbered)
2534 add_line_number (p);
2536 empty_line = FALSE;
2537 if (c == '\n')
2538 return TRUE;
2540 print_clump (p, chars, clump_buff);
2542 for (;;)
2544 c = getc (p->fp);
2546 switch (c)
2548 case '\n':
2549 return TRUE;
2550 case '\f':
2551 if ((c = getc (p->fp)) != '\n')
2552 ungetc (c, p->fp);
2553 if (keep_FF)
2554 print_a_FF = TRUE;
2555 hold_file (p);
2556 return TRUE;
2557 case EOF:
2558 close_file (p);
2559 return TRUE;
2562 last_input_position = input_position;
2563 chars = char_to_clump (c);
2564 if (truncate_lines && input_position > chars_per_column)
2566 input_position = last_input_position;
2567 return FALSE;
2570 print_clump (p, chars, clump_buff);
2574 /* Print a line from buff.
2576 If this function has been called, we know we have "something to
2577 print". But it remains to be seen whether we have a real text page
2578 or an empty page (a single form feed) with/without a header only.
2579 Therefore first we set pad_vertically to TRUE and print a header
2580 if necessary.
2581 If FF_FOUND and we are using -t|-T option we omit any newline by
2582 setting pad_vertically to FALSE (see print_page).
2583 Otherwise we pad across if necessary, print separators if necessary
2584 and text of COLUMN *p.
2586 Return TRUE, meaning there is no need to call read_rest_of_line. */
2588 static int
2589 print_stored (COLUMN *p)
2591 COLUMN *q;
2592 int i;
2594 int line = p->current_line++;
2595 register char *first = &buff[line_vector[line]];
2596 /* FIXME
2597 UMR: Uninitialized memory read:
2598 * This is occurring while in:
2599 print_stored [pr.c:2239]
2600 * Reading 4 bytes from 0x5148c in the heap.
2601 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2602 * This block was allocated from:
2603 malloc [rtlib.o]
2604 xmalloc [xmalloc.c:94]
2605 init_store_cols [pr.c:1648]
2607 register char *last = &buff[line_vector[line + 1]];
2609 pad_vertically = TRUE;
2611 if (print_a_header)
2612 print_header ();
2614 if (p->status == FF_FOUND)
2616 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2617 q->status = ON_HOLD;
2618 if (column_vector->lines_to_print <= 0)
2620 if (!extremities)
2621 pad_vertically = FALSE;
2622 return TRUE; /* print a header only */
2626 if (padding_not_printed - col_sep_length > 0)
2628 pad_across_to (padding_not_printed - col_sep_length);
2629 padding_not_printed = ANYWHERE;
2632 if (use_col_separator)
2633 print_sep_string ();
2635 while (first != last)
2636 print_char (*first++);
2638 if (spaces_not_printed == 0)
2640 output_position = p->start_position + end_vector[line];
2641 if (p->start_position - col_sep_length == chars_per_margin)
2642 output_position -= col_sep_length;
2645 return TRUE;
2648 /* Convert a character to the proper format and return the number of
2649 characters in the resulting clump. Increment input_position by
2650 the width of the clump.
2652 Tabs are converted to clumps of spaces.
2653 Nonprintable characters may be converted to clumps of escape
2654 sequences or control prefixes.
2656 Note: the width of a clump is not necessarily equal to the number of
2657 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2658 number of characters is 1.) */
2660 static int
2661 char_to_clump (int c)
2663 register int *s = clump_buff;
2664 register int i;
2665 char esc_buff[4];
2666 int width;
2667 int chars;
2668 int chars_per_c = 8;
2670 if (c == input_tab_char)
2671 chars_per_c = chars_per_input_tab;
2673 if (c == input_tab_char || c == '\t')
2675 width = TAB_WIDTH (chars_per_c, input_position);
2677 if (untabify_input)
2679 for (i = width; i; --i)
2680 *s++ = ' ';
2681 chars = width;
2683 else
2685 *s = c;
2686 chars = 1;
2690 else if (!ISPRINT (c))
2692 if (use_esc_sequence)
2694 width = 4;
2695 chars = 4;
2696 *s++ = '\\';
2697 sprintf (esc_buff, "%03o", c);
2698 for (i = 0; i <= 2; ++i)
2699 *s++ = (int) esc_buff[i];
2701 else if (use_cntrl_prefix)
2703 if (c < 0200)
2705 width = 2;
2706 chars = 2;
2707 *s++ = '^';
2708 *s++ = c ^ 0100;
2710 else
2712 width = 4;
2713 chars = 4;
2714 *s++ = '\\';
2715 sprintf (esc_buff, "%03o", c);
2716 for (i = 0; i <= 2; ++i)
2717 *s++ = (int) esc_buff[i];
2720 else if (c == '\b')
2722 width = -1;
2723 chars = 1;
2724 *s = c;
2726 else
2728 width = 0;
2729 chars = 1;
2730 *s = c;
2733 else
2735 width = 1;
2736 chars = 1;
2737 *s = c;
2740 input_position += width;
2741 return chars;
2744 /* We've just printed some files and need to clean up things before
2745 looking for more options and printing the next batch of files.
2747 Free everything we've xmalloc'ed, except `header'. */
2749 static void
2750 cleanup (void)
2752 if (number_buff)
2753 free (number_buff);
2754 if (clump_buff)
2755 free (clump_buff);
2756 if (column_vector)
2757 free (column_vector);
2758 if (line_vector)
2759 free (line_vector);
2760 if (end_vector)
2761 free (end_vector);
2762 if (buff)
2763 free (buff);
2766 /* Complain, print a usage message, and die. */
2768 void
2769 usage (int status)
2771 if (status != 0)
2772 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2773 program_name);
2774 else
2776 printf (_("\
2777 Usage: %s [OPTION]... [FILE]...\n\
2779 program_name);
2781 printf (_("\
2782 Paginate or columnate FILE(s) for printing.\n\
2784 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2785 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2786 -COLUMN, --columns=COLUMN\n\
2787 produce COLUMN-column output and print columns down,\n\
2788 unless -a is used. Balance number of lines in the\n\
2789 columns on each page.\n\
2790 -a, --across print columns across rather than down, used together\n\
2791 with -COLUMN\n\
2792 -c, --show-control-chars\n\
2793 use hat notation (^G) and octal backslash notation\n\
2794 -d, --double-space\n\
2795 double space the output\n\
2796 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2797 expand input CHARs (TABs) to tab WIDTH (8)\n\
2798 -F, -f, --form-feed\n\
2799 use form feeds instead of newlines to separate pages\n\
2800 (by a 3-line page header with -F or a 5-line header\n\
2801 and trailer without -F)\n\
2802 "));
2803 printf (_("\
2804 -h HEADER, --header=HEADER\n\
2805 use a centered HEADER instead of filename in page header,\n\
2806 with long headers left-hand-side truncation may occur,\n\
2807 -h \"\" prints a blank line, don't use -h\"\"\n\
2808 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2809 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2810 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2811 alignment, -S[STRING] sets separators\n\
2812 -l PAGE_LENGTH, --length=PAGE_LENGTH\n\
2813 set the page length to PAGE_LENGTH (66) lines\n\
2814 (default number of lines of text 56, and with -F 63)\n\
2815 -m, --merge print all files in parallel, one in each column,\n\
2816 truncate lines, but join lines of full length with -J\n\
2817 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2818 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2819 default counting starts with 1st line of input file\n\
2820 -N NUMBER, --first-line-number=NUMBER\n\
2821 start counting with NUMBER at 1st line of first\n\
2822 page printed (see +FIRST_PAGE)\n\
2823 -o MARGIN, --indent=MARGIN\n\
2824 offset each line with MARGIN (zero) spaces, do not\n\
2825 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2826 -r, --no-file-warnings\n\
2827 omit warning when a file cannot be opened\n\
2828 "));
2829 printf (_("\
2830 -s[CHAR],--separator[=CHAR]\n\
2831 separate columns by a single character, default for CHAR\n\
2832 is the <TAB> character without -w and \'no char\' with -w\n\
2833 -s[CHAR] turns off line truncation of all 3 column\n\
2834 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2835 -S[STRING], --sep-string[=STRING]\n\
2836 separate columns by an optional STRING, don't use\n\
2837 -S \"STRING\", -S only: No separator used (same as -S\"\"),\n\
2838 without -S: Default separator <TAB> with -J and <space>\n\
2839 otherwise (same as -S\" \"), no effect on column options\n\
2840 -t, --omit-header omit page headers and trailers\n\
2841 -T, --omit-pagination\n\
2842 omit page headers and trailers, eliminate any pagination\n\
2843 by form feeds set in input files\n\
2844 -v, --show-nonprinting\n\
2845 use octal backslash notation\n\
2846 -w PAGE_WIDTH, --width=PAGE_WIDTH\n\
2847 set page width to PAGE_WIDTH (72) characters for\n\
2848 multiple text-column output only, -s[char] turns off (72)\n\
2849 -W PAGE_WIDTH, --page-width=PAGE_WIDTH\n\
2850 set page width to PAGE_WIDTH (72) characters always,\n\
2851 truncate lines, except -J option is set, no interference\n\
2852 with -S or -s\n\
2853 --help display this help and exit\n\
2854 --version output version information and exit\n\
2856 -T implied by -l nn when nn <= 10 or <= 3 with -F. With no FILE, or when\n\
2857 FILE is -, read standard input.\n\
2858 "));
2859 puts (_("\nReport bugs to <bug-textutils@gnu.org>."));
2861 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);