*** empty log message ***
[coreutils.git] / src / pr.c
blobf5b22cc0578a865b6a22b59ec3bef4baf9052127
1 /* pr -- convert text files for printing.
2 Copyright (C) 88, 91, 1995-2002 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 options:
80 -w l -s[x]
81 --------------------------------------------------------------------
82 1. -- -- columns / space --
83 trunc. to page_width = 72
84 2. -- -s[:] full lines / TAB[:] -J --sep-string[="<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 --sep-string[=:]
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 -D FORMAT, --date-format=FORMAT Use FORMAT for the header date.
155 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]
156 Expand tabs to spaces on input. Optional argument CHAR
157 is the input TAB character. (Default is TAB). Optional
158 argument WIDTH is the input TAB character's width.
159 (Default is 8.)
161 -F, -f, --form-feed Use formfeeds instead of newlines to separate
162 pages. A three line HEADER is used, no TRAILER with -F,
163 without -F both HEADER and TRAILER are made of five lines.
165 -h HEADER, --header=HEADER
166 Replace the filename in the header with the string HEADER.
167 A centered header is used.
169 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]
170 Replace spaces with tabs on output. Optional argument
171 CHAR is the output TAB character. (Default is TAB).
172 Optional argument WIDTH is the output TAB character's
173 width. (Default is 8)
175 -J, --join-lines Merge lines of full length, turns off -W/-w
176 line truncation, no column alignment, --sep-string[=STRING]
177 sets separators, works with all column options
178 (-COLUMN | -a -COLUMN | -m).
179 -J has been introduced (together with -W and --sep-string) to
180 disentangle the old (POSIX compliant) options -w, -s
181 along with the 3 column options.
183 -l PAGE_LENGTH, --length=PAGE_LENGTH
184 Set the page length to PAGE_LENGTH lines. Default is 66,
185 including 5 lines of HEADER and 5 lines of TRAILER
186 without -F, but only 3 lines of HEADER and no TRAILER
187 with -F (i.e the number of text lines defaults to 56 or
188 63 respectively).
190 -m, --merge Print files in parallel; pad_across_to align
191 columns; truncate lines and print separator strings;
192 Do it also with empty columns to get a continuous line
193 numbering and column marking by separators throughout
194 the whole merged file.
196 Empty pages in some input files produce empty columns
197 [marked by separators] in the merged pages. Completely
198 empty merged pages show no column separators at all.
200 The layout of a merged page is ruled by the largest form
201 feed distance of the single pages at that page. Shorter
202 columns will be filled up with empty lines.
204 Together with -J option join lines of full length and
205 set separators when -S option is used.
207 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]
208 Provide DIGITS digit line numbering (default for DIGITS
209 is 5). With multicolumn output the number occupies the
210 first DIGITS column positions of each text column or only
211 each line of -m output.
212 With single column output the number precedes each line
213 just as -m output.
214 Optional argument SEP is the character appended to the
215 line number to separate it from the text followed.
216 The default separator is a TAB. In a strict sense a TAB
217 is always printed with single column output only. The
218 TAB-width varies with the TAB-position, e.g. with the
219 left margin specified by -o option.
220 With multicolumn output priority is given to `equal width
221 of output columns' (a POSIX specification). The TAB-width
222 is fixed to the value of the 1st column and does not
223 change with different values of left margin. That means a
224 fixed number of spaces is always printed in the place of
225 a TAB. The tabification depends upon the output
226 position.
228 Default counting of the line numbers starts with 1st
229 line of the input file (not the 1st line printed,
230 compare the --page option and -N option).
232 -N NUMBER, --first-line-number=NUMBER
233 Start line counting with the number NUMBER at the 1st
234 line of first page printed (mostly not the 1st line of
235 the input file).
237 -o MARGIN, --indent=MARGIN
238 Offset each line with a margin MARGIN spaces wide.
239 Total page width is the size of the margin plus the
240 PAGE_WIDTH set with -W/-w option.
242 -r, --no-file-warnings
243 Omit warning when a file cannot be opened.
245 -s[CHAR], --separator[=CHAR]
246 Separate columns by a single character CHAR, default for
247 CHAR is the TAB character without -w and 'no char' with -w.
248 Without `-s' default separator `space' is set.
249 -s[CHAR] turns off line truncation of all 3 column options
250 (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX
251 compliant formulation. The source code translates -s into
252 the new options -S and -J, also -W if required.
254 -S STRING, --sep-string[=STRING]
255 Separate columns by any string STRING. The -S option
256 doesn't react upon the -W/-w option (unlike -s option
257 does). It defines a separator nothing else.
258 Without -S: Default separator TAB is used with -J and
259 `space' otherwise (same as -S" ").
260 With -S "": No separator is used.
261 Quotes should be used with blanks and some shell active
262 characters.
263 -S is problematic because in its obsolete form you
264 cannot use -S "STRING", but in its standard form you
265 must use -S "STRING" if STRING is empty. Use
266 --sep-string to avoid the ambiguity.
268 -t, --omit-header Do not print headers or footers but retain form
269 feeds set in the input files.
271 -T, --omit-pagination
272 Do not print headers or footers, eliminate any pagination
273 by form feeds set in the input files.
275 -v, --show-nonprinting
276 Print unprintable characters as escape sequences. Use
277 octal backslash notation. Control-G becomes \007.
279 -w PAGE_WIDTH, --width=PAGE_WIDTH
280 Set page width to PAGE_WIDTH characters for multiple
281 text-column output only (default for PAGE_WIDTH is 72).
282 -s[CHAR] turns off the default page width and any line
283 truncation. Lines of full length will be merged,
284 regardless of the column options set. A POSIX compliant
285 formulation.
287 -W PAGE_WIDTH, --page-width=PAGE_WIDTH
288 Set the page width to PAGE_WIDTH characters. That's valid
289 with and without a column option. Text lines will be
290 truncated, unless -J is used. Together with one of the
291 column options (-COLUMN| -a -COLUMN| -m) column alignment
292 is always used.
293 Default is 72 characters.
294 Without -W PAGE_WIDTH
295 - but with one of the column options default truncation of
296 72 characters is used (to keep downward compatibility
297 and to simplify most frequently met column tasks).
298 Column alignment and column separators are used.
299 - and without any of the column options NO line truncation
300 is used (to keep downward compatibility and to meet most
301 frequent tasks). That's equivalent to -W 72 -J .
303 With/without -W PAGE_WIDTH the header line is always
304 truncated to avoid line overflow.
306 (In pr versions newer than 1.14 -S option does no longer
307 affect -W option.)
312 #include <config.h>
314 #include <stdio.h>
315 #include <getopt.h>
316 #include <sys/types.h>
317 #include <time.h>
318 #include "system.h"
319 #include "closeout.h"
320 #include "error.h"
321 #include "mbswidth.h"
322 #include "posixver.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 N_ ("Pete TerMaat and Roland Huebner")
330 #ifndef TRUE
331 # define TRUE 1
332 # define FALSE 0
333 #endif
335 /* Used with start_position in the struct COLUMN described below.
336 If start_position == ANYWHERE, we aren't truncating columns and
337 can begin printing a column anywhere. Otherwise we must pad to
338 the horizontal position start_position. */
339 #define ANYWHERE 0
341 /* Each column has one of these structures allocated for it.
342 If we're only dealing with one file, fp is the same for all
343 columns.
345 The general strategy is to spend time setting up these column
346 structures (storing columns if necessary), after which printing
347 is a matter of flitting from column to column and calling
348 print_func.
350 Parallel files, single files printing across in multiple
351 columns, and single files printing down in multiple columns all
352 fit the same printing loop.
354 print_func Function used to print lines in this column.
355 If we're storing this column it will be
356 print_stored(), Otherwise it will be read_line().
358 char_func Function used to process characters in this column.
359 If we're storing this column it will be store_char(),
360 otherwise it will be print_char().
362 current_line Index of the current entry in line_vector, which
363 contains the index of the first character of the
364 current line in buff[].
366 lines_stored Number of lines in this column which are stored in
367 buff.
369 lines_to_print If we're storing this column, lines_to_print is
370 the number of stored_lines which remain to be
371 printed. Otherwise it is the number of lines
372 we can print without exceeding lines_per_body.
374 start_position The horizontal position we want to be in before we
375 print the first character in this column.
377 numbered True means precede this column with a line number. */
379 struct COLUMN;
380 struct COLUMN
382 FILE *fp; /* Input stream for this column. */
383 char const *name; /* File name. */
384 enum
386 OPEN,
387 FF_FOUND, /* used with -b option, set with \f, changed
388 to ON_HOLD after print_header */
389 ON_HOLD, /* Hit a form feed. */
390 CLOSED
392 status; /* Status of the file pointer. */
394 /* Func to print lines in this col. */
395 int (*print_func) PARAMS ((struct COLUMN *));
397 /* Func to print/store chars in this col. */
398 void (*char_func) PARAMS ((int));
400 int current_line; /* Index of current place in line_vector. */
401 int lines_stored; /* Number of lines stored in buff. */
402 int lines_to_print; /* No. lines stored or space left on page. */
403 int start_position; /* Horizontal position of first char. */
404 int numbered;
405 int full_page_printed; /* True means printed without a FF found. */
407 /* p->full_page_printed controls a special case of "FF set by hand":
408 True means a full page has been printed without FF found. To avoid an
409 additional empty page we have to ignore a FF immediately following in
410 the next line. */
413 typedef struct COLUMN COLUMN;
415 #define NULLCOL (COLUMN *)0
417 static int char_to_clump PARAMS ((int c));
418 static int read_line PARAMS ((COLUMN *p));
419 static int print_page PARAMS ((void));
420 static int print_stored PARAMS ((COLUMN *p));
421 static int open_file PARAMS ((char *name, COLUMN *p));
422 static int skip_to_page PARAMS ((int page));
423 static void print_header PARAMS ((void));
424 static void pad_across_to PARAMS ((int position));
425 static void add_line_number PARAMS ((COLUMN *p));
426 static void getoptarg PARAMS ((char *arg, char switch_char, char *character,
427 int *number));
428 void usage PARAMS ((int status));
429 static void print_files PARAMS ((int number_of_files, char **av));
430 static void init_parameters PARAMS ((int number_of_files));
431 static void init_header PARAMS ((char *filename, int desc));
432 static int init_fps PARAMS ((int number_of_files, char **av));
433 static void init_funcs PARAMS ((void));
434 static void init_store_cols PARAMS ((void));
435 static void store_columns PARAMS ((void));
436 static void balance PARAMS ((int total_stored));
437 static void store_char PARAMS ((int c));
438 static void pad_down PARAMS ((int lines));
439 static void read_rest_of_line PARAMS ((COLUMN *p));
440 static void skip_read PARAMS ((COLUMN *p, int column_number));
441 static void print_char PARAMS ((int c));
442 static void cleanup PARAMS ((void));
443 static void first_last_page PARAMS ((char *pages));
444 static void print_sep_string PARAMS ((void));
445 static void separator_string PARAMS ((const char *optarg_S));
447 /* The name under which this program was invoked. */
448 char *program_name;
450 /* All of the columns to print. */
451 static COLUMN *column_vector;
453 /* When printing a single file in multiple downward columns,
454 we store the leftmost columns contiguously in buff.
455 To print a line from buff, get the index of the first character
456 from line_vector[i], and print up to line_vector[i + 1]. */
457 static char *buff;
459 /* Index of the position in buff where the next character
460 will be stored. */
461 static int buff_current;
463 /* The number of characters in buff.
464 Used for allocation of buff and to detect overflow of buff. */
465 static int buff_allocated;
467 /* Array of indices into buff.
468 Each entry is an index of the first character of a line.
469 This is used when storing lines to facilitate shuffling when
470 we do column balancing on the last page. */
471 static int *line_vector;
473 /* Array of horizonal positions.
474 For each line in line_vector, end_vector[line] is the horizontal
475 position we are in after printing that line. We keep track of this
476 so that we know how much we need to pad to prepare for the next
477 column. */
478 static int *end_vector;
480 /* (-m) True means we're printing multiple files in parallel. */
481 static int parallel_files = FALSE;
483 /* (-m) True means a line starts with some empty columns (some files
484 already CLOSED or ON_HOLD) which we have to align. */
485 static int align_empty_cols;
487 /* (-m) True means we have not yet found any printable column in a line.
488 align_empty_cols = TRUE has to be maintained. */
489 static int empty_line;
491 /* (-m) False means printable column output precedes a form feed found.
492 Column alignment is done only once. No additional action with that form
493 feed.
494 True means we found only a form feed in a column. Maybe we have to do
495 some column alignment with that form feed. */
496 static int FF_only;
498 /* (-[0-9]+) True means we're given an option explicitly specifying
499 number of columns. Used to detect when this option is used with -m
500 and when translating old options to new/long options. */
501 static int explicit_columns = FALSE;
503 /* (-t|-T) False means we aren't printing headers and footers. */
504 static int extremities = TRUE;
506 /* (-t) True means we retain all FF set by hand in input files.
507 False is set with -T option. */
508 static int keep_FF = FALSE;
509 static int print_a_FF = FALSE;
511 /* True means we need to print a header as soon as we know we've got input
512 to print after it. */
513 static int print_a_header;
515 /* (-f) True means use formfeeds instead of newlines to separate pages. */
516 static int use_form_feed = FALSE;
518 /* True means we have read the standard input. */
519 static int have_read_stdin = FALSE;
521 /* True means the -a flag has been given. */
522 static int print_across_flag = FALSE;
524 /* True means we're printing one file in multiple (>1) downward columns. */
525 static int storing_columns = TRUE;
527 /* (-b) True means balance columns on the last page as Sys V does. */
528 /* That's no longer an independent option. With storing_columns = TRUE
529 balance_columns = TRUE is used too (s. function init_parameters).
530 We get a consistent formulation with "FF set by hand" in input files. */
531 static int balance_columns = FALSE;
533 /* (-l) Number of lines on a page, including header and footer lines. */
534 static int lines_per_page = 66;
536 /* Number of lines in the header and footer can be reset to 0 using
537 the -t flag. */
538 static int lines_per_header = 5;
539 static int lines_per_body;
540 static int lines_per_footer = 5;
542 /* (-w|-W) Width in characters of the page. Does not include the width of
543 the margin. */
544 static int chars_per_line = 72;
546 /* (-w|W) True means we truncate lines longer than chars_per_column. */
547 static int truncate_lines = FALSE;
549 /* (-J) True means we join lines without any line truncation. -J
550 dominates -w option. */
551 static int join_lines = FALSE;
553 /* Number of characters in a column. Based on col_sep_length and
554 page width. */
555 static int chars_per_column;
557 /* (-e) True means convert tabs to spaces on input. */
558 static int untabify_input = FALSE;
560 /* (-e) The input tab character. */
561 static char input_tab_char = '\t';
563 /* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
564 where the leftmost column is 1. */
565 static int chars_per_input_tab = 8;
567 /* (-i) True means convert spaces to tabs on output. */
568 static int tabify_output = FALSE;
570 /* (-i) The output tab character. */
571 static char output_tab_char = '\t';
573 /* (-i) The width of the output tab. */
574 static int chars_per_output_tab = 8;
576 /* Keeps track of pending white space. When we hit a nonspace
577 character after some whitespace, we print whitespace, tabbing
578 if necessary to get to output_position + spaces_not_printed. */
579 static int spaces_not_printed;
581 /* (-o) Number of spaces in the left margin (tabs used when possible). */
582 static int chars_per_margin = 0;
584 /* Position where the next character will fall.
585 Leftmost position is 0 + chars_per_margin.
586 Rightmost position is chars_per_margin + chars_per_line - 1.
587 This is important for converting spaces to tabs on output. */
588 static int output_position;
590 /* Horizontal position relative to the current file.
591 (output_position depends on where we are on the page;
592 input_position depends on where we are in the file.)
593 Important for converting tabs to spaces on input. */
594 static int input_position;
596 /* Count number of failed opens so we can exit with nonzero
597 status if there were any. */
598 static int failed_opens = 0;
600 /* The number of spaces taken up if we print a tab character with width
601 c_ from position h_. */
602 #define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
604 /* The horizontal position we'll be at after printing a tab character
605 of width c_ from the position h_. */
606 #define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
608 /* (-NNN) Number of columns of text to print. */
609 static int columns = 1;
611 /* (+NNN:MMM) Page numbers on which to begin and stop printing.
612 first_page_number = 0 will be used to check input only. */
613 static int first_page_number = 0;
614 static int last_page_number = 0;
616 /* Number of files open (not closed, not on hold). */
617 static int files_ready_to_read = 0;
619 /* Current page number. Displayed in header. */
620 static int page_number;
622 /* Current line number. Displayed when -n flag is specified.
624 When printing files in parallel (-m flag), line numbering is as follows:
625 1 foo goo moo
626 2 hoo too zoo
628 When printing files across (-a flag), ...
629 1 foo 2 moo 3 goo
630 4 hoo 5 too 6 zoo
632 Otherwise, line numbering is as follows:
633 1 foo 3 goo 5 too
634 2 moo 4 hoo 6 zoo */
635 static int line_number;
637 /* With line_number overflow, we use power_10 to cut off the higher-order
638 digits of the line_number */
639 static int power_10;
641 /* (-n) True means lines should be preceded by numbers. */
642 static int numbered_lines = FALSE;
644 /* (-n) Character which follows each line number. */
645 static char number_separator = '\t';
647 /* (-n) line counting starts with 1st line of input file (not with 1st
648 line of 1st page printed). */
649 static int line_count = 1;
651 /* (-n) True means counting of skipped lines starts with 1st line of
652 input file. False means -N option is used in addition, counting of
653 skipped lines not required. */
654 static int skip_count = TRUE;
656 /* (-N) Counting starts with start_line_number = NUMBER at 1st line of
657 first page printed, usually not 1st page of input file. */
658 static int start_line_num = 1;
660 /* (-n) Width in characters of a line number. */
661 static int chars_per_number = 5;
663 /* Used when widening the first column to accommodate numbers -- only
664 needed when printing files in parallel. Includes width of both the
665 number and the number_separator. */
666 static int number_width;
668 /* Buffer sprintf uses to format a line number. */
669 static char *number_buff;
671 /* (-v) True means unprintable characters are printed as escape sequences.
672 control-g becomes \007. */
673 static int use_esc_sequence = FALSE;
675 /* (-c) True means unprintable characters are printed as control prefixes.
676 control-g becomes ^G. */
677 static int use_cntrl_prefix = FALSE;
679 /* (-d) True means output is double spaced. */
680 static int double_space = FALSE;
682 /* Number of files opened initially in init_files. Should be 1
683 unless we're printing multiple files in parallel. */
684 static int total_files = 0;
686 /* (-r) True means don't complain if we can't open a file. */
687 static int ignore_failed_opens = FALSE;
689 /* (-S) True means we separate columns with a specified string.
690 -S option does not affect line truncation nor column alignment. */
691 static int use_col_separator = FALSE;
693 /* String used to separate columns if the -S option has been specified.
694 Default without -S but together with one of the column options
695 -a|COLUMN|-m is a `space' and with the -J option a `tab'. */
696 static char *col_sep_string = "";
697 static int col_sep_length = 0;
698 static char *column_separator = " ";
699 static char *line_separator = "\t";
701 /* Number of separator characters waiting to be printed as soon as we
702 know that we have any input remaining to be printed. */
703 static int separators_not_printed;
705 /* Position we need to pad to, as soon as we know that we have input
706 remaining to be printed. */
707 static int padding_not_printed;
709 /* True means we should pad the end of the page. Remains false until we
710 know we have a page to print. */
711 static int pad_vertically;
713 /* (-h) String of characters used in place of the filename in the header. */
714 static char *custom_header;
716 /* (-D) Date format for the header. */
717 static char const *date_format;
719 /* Date and file name for the header. */
720 static char *date_text;
721 static char const *file_text;
723 /* Output columns available, not counting the date and file name. */
724 static int header_width_available;
726 static int *clump_buff;
728 /* True means we read the line no. lines_per_body in skip_read
729 called by skip_to_page. That variable controls the coincidence of a
730 "FF set by hand" and "full_page_printed", see above the definition of
731 structure COLUMN. */
732 static int last_line = FALSE;
734 /* For long options that have no equivalent short option, use a
735 non-character as a pseudo short option, starting with CHAR_MAX + 1. */
736 enum
738 COLUMNS_OPTION = CHAR_MAX + 1,
739 PAGES_OPTION
742 #define COMMON_SHORT_OPTIONS \
743 "-0123456789D:FJN:TW:abcde::fh:i::l:mn::o:rs::tvw:"
745 static struct option const long_options[] =
747 {"pages", required_argument, NULL, PAGES_OPTION},
748 {"columns", required_argument, NULL, COLUMNS_OPTION},
749 {"across", no_argument, NULL, 'a'},
750 {"show-control-chars", no_argument, NULL, 'c'},
751 {"double-space", no_argument, NULL, 'd'},
752 {"date-format", required_argument, NULL, 'D'},
753 {"expand-tabs", optional_argument, NULL, 'e'},
754 {"form-feed", no_argument, NULL, 'f'},
755 {"header", required_argument, NULL, 'h'},
756 {"output-tabs", optional_argument, NULL, 'i'},
757 {"join-lines", no_argument, NULL, 'J'},
758 {"length", required_argument, NULL, 'l'},
759 {"merge", no_argument, NULL, 'm'},
760 {"number-lines", optional_argument, NULL, 'n'},
761 {"first-line-number", required_argument, NULL, 'N'},
762 {"indent", required_argument, NULL, 'o'},
763 {"no-file-warnings", no_argument, NULL, 'r'},
764 {"separator", optional_argument, NULL, 's'},
765 {"sep-string", optional_argument, NULL, 'S'},
766 {"omit-header", no_argument, NULL, 't'},
767 {"omit-pagination", no_argument, NULL, 'T'},
768 {"show-nonprinting", no_argument, NULL, 'v'},
769 {"width", required_argument, NULL, 'w'},
770 {"page-width", required_argument, NULL, 'W'},
771 {GETOPT_HELP_OPTION_DECL},
772 {GETOPT_VERSION_OPTION_DECL},
773 {0, 0, 0, 0}
776 /* Return the number of columns that have either an open file or
777 stored lines. */
779 static int
780 cols_ready_to_print (void)
782 COLUMN *q;
783 int i;
784 int n;
786 n = 0;
787 for (q = column_vector, i = 0; i < columns; ++q, ++i)
788 if (q->status == OPEN ||
789 q->status == FF_FOUND || /* With -b: To print a header only */
790 (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
791 ++n;
792 return n;
795 /* Estimate first_ / last_page_number
796 using option +FIRST_PAGE:LAST_PAGE */
798 static void
799 first_last_page (char *pages)
801 char *str1;
803 if (*pages == ':')
805 error (0, 0, _("`--pages' invalid range of page numbers: `%s'"), pages);
806 usage (2);
809 str1 = strchr (pages, ':');
810 if (str1 != NULL)
811 *str1 = '\0';
814 long int tmp_long;
815 if (xstrtol (pages, NULL, 10, &tmp_long, "") != LONGINT_OK
816 || tmp_long < 1 || tmp_long > INT_MAX)
817 error (EXIT_FAILURE, 0, _("`--pages' invalid starting page number: `%s'"),
818 pages);
819 first_page_number = (int) tmp_long;
822 if (str1 == NULL)
823 return;
826 long int tmp_long;
827 if (xstrtol (str1 + 1, NULL, 10, &tmp_long, "") != LONGINT_OK
828 || tmp_long <= 0 || tmp_long > INT_MAX)
829 error (EXIT_FAILURE, 0, _("`--pages' invalid ending page number: `%s'"),
830 str1 + 1);
831 last_page_number = (int) tmp_long;
834 if (first_page_number > last_page_number)
835 error (EXIT_FAILURE, 0,
836 _("`--pages' starting page number is larger than ending page number"));
839 /* Estimate length of col_sep_string with option -S. */
841 static void
842 separator_string (const char *optarg_S)
844 col_sep_length = (int) strlen (optarg_S);
845 col_sep_string = (char *) xmalloc (col_sep_length + 1);
846 strcpy (col_sep_string, optarg_S);
850 main (int argc, char **argv)
852 int c;
853 int accum = 0;
854 int n_files;
855 int old_options = FALSE;
856 int old_w = FALSE;
857 int old_s = FALSE;
858 char **file_names;
859 char const *short_options = (posix2_version () < 200112
860 ? COMMON_SHORT_OPTIONS "S::"
861 : COMMON_SHORT_OPTIONS "S:");
863 program_name = argv[0];
864 setlocale (LC_ALL, "");
865 bindtextdomain (PACKAGE, LOCALEDIR);
866 textdomain (PACKAGE);
868 atexit (close_stdout);
870 n_files = 0;
871 file_names = (argc > 1
872 ? (char **) xmalloc ((argc - 1) * sizeof (char *))
873 : NULL);
875 while ((c = getopt_long (argc, argv, short_options, long_options, NULL))
876 != -1)
878 if (ISDIGIT (c))
880 accum = accum * 10 + c - '0';
881 continue;
884 if (accum > 0)
886 columns = accum;
887 explicit_columns = TRUE;
888 accum = 0;
891 switch (c)
893 case 0: /* getopt long option */
894 break;
896 case 1: /* Non-option argument. */
897 if (*optarg == '+')
899 /* long option --page dominates old `+FIRST_PAGE ...' */
900 if (first_page_number <= 0 && last_page_number <= 0)
901 first_last_page (optarg);
903 else
904 file_names[n_files++] = optarg;
905 break;
907 case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
908 { /* dominates old opt +... */
909 if (optarg)
910 first_last_page (optarg);
911 else
912 error (EXIT_FAILURE, 0,
913 _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
914 break;
917 case COLUMNS_OPTION: /* --columns=COLUMN */
919 long int tmp_long;
920 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
921 || tmp_long <= 0 || tmp_long > INT_MAX)
923 error (EXIT_FAILURE, 0,
924 _("`--columns=COLUMN' invalid number of columns: `%s'"),
925 optarg);
927 columns = (int) tmp_long;
928 break;
931 case 'a':
932 print_across_flag = TRUE;
933 storing_columns = FALSE;
934 break;
935 case 'b':
936 balance_columns = TRUE;
937 break;
938 case 'c':
939 use_cntrl_prefix = TRUE;
940 break;
941 case 'd':
942 double_space = TRUE;
943 break;
944 case 'D':
945 date_format = optarg;
946 break;
947 case 'e':
948 if (optarg)
949 getoptarg (optarg, 'e', &input_tab_char,
950 &chars_per_input_tab);
951 /* Could check tab width > 0. */
952 untabify_input = TRUE;
953 break;
954 case 'f':
955 case 'F':
956 use_form_feed = TRUE;
957 break;
958 case 'h':
959 custom_header = optarg;
960 break;
961 case 'i':
962 if (optarg)
963 getoptarg (optarg, 'i', &output_tab_char,
964 &chars_per_output_tab);
965 /* Could check tab width > 0. */
966 tabify_output = TRUE;
967 break;
968 case 'J':
969 join_lines = TRUE;
970 break;
971 case 'l':
973 long int tmp_long;
974 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
975 || tmp_long <= 0 || tmp_long > INT_MAX)
977 error (EXIT_FAILURE, 0,
978 _("`-l PAGE_LENGTH' invalid number of lines: `%s'"),
979 optarg);
981 lines_per_page = (int) tmp_long;
982 break;
984 case 'm':
985 parallel_files = TRUE;
986 storing_columns = FALSE;
987 break;
988 case 'n':
989 numbered_lines = TRUE;
990 if (optarg)
991 getoptarg (optarg, 'n', &number_separator,
992 &chars_per_number);
993 break;
994 case 'N':
995 skip_count = FALSE;
997 long int tmp_long;
998 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
999 || tmp_long > INT_MAX)
1001 error (EXIT_FAILURE, 0,
1002 _("`-N NUMBER' invalid starting line number: `%s'"),
1003 optarg);
1005 start_line_num = (int) tmp_long;
1006 break;
1008 case 'o':
1010 long int tmp_long;
1011 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1012 || tmp_long < 0 || tmp_long > INT_MAX)
1013 error (EXIT_FAILURE, 0,
1014 _("`-o MARGIN' invalid line offset: `%s'"), optarg);
1015 chars_per_margin = (int) tmp_long;
1016 break;
1018 case 'r':
1019 ignore_failed_opens = TRUE;
1020 break;
1021 case 's':
1022 old_options = TRUE;
1023 old_s = TRUE;
1024 if (!use_col_separator && optarg)
1025 separator_string (optarg);
1026 break;
1027 case 'S':
1028 old_s = FALSE;
1029 /* Reset an additional input of -s, -S dominates -s */
1030 col_sep_string = "";
1031 col_sep_length = 0;
1032 use_col_separator = TRUE;
1033 if (optarg)
1034 separator_string (optarg);
1035 break;
1036 case 't':
1037 extremities = FALSE;
1038 keep_FF = TRUE;
1039 break;
1040 case 'T':
1041 extremities = FALSE;
1042 keep_FF = FALSE;
1043 break;
1044 case 'v':
1045 use_esc_sequence = TRUE;
1046 break;
1047 case 'w':
1048 old_options = TRUE;
1049 old_w = TRUE;
1051 long int tmp_long;
1052 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1053 || tmp_long <= 0 || tmp_long > INT_MAX)
1054 error (EXIT_FAILURE, 0,
1055 _("`-w PAGE_WIDTH' invalid number of characters: `%s'"), optarg);
1056 if (!truncate_lines) chars_per_line = (int) tmp_long;
1057 break;
1059 case 'W':
1060 old_w = FALSE; /* dominates -w */
1061 truncate_lines = TRUE;
1063 long int tmp_long;
1064 if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
1065 || tmp_long <= 0 || tmp_long > INT_MAX)
1066 error (EXIT_FAILURE, 0,
1067 _("`-W PAGE_WIDTH' invalid number of characters: `%s'"), optarg);
1068 chars_per_line = (int) tmp_long;
1069 break;
1071 case_GETOPT_HELP_CHAR;
1072 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
1073 default:
1074 usage (2);
1075 break;
1079 if (! date_format)
1080 date_format = (getenv ("POSIXLY_CORRECT")
1081 ? dcgettext (NULL, "%b %e %H:%M %Y", LC_TIME)
1082 : "%Y-%m-%d %H:%M");
1084 /* Now we can set a reasonable initial value: */
1085 if (first_page_number == 0)
1086 first_page_number = 1;
1088 if (parallel_files && explicit_columns)
1089 error (EXIT_FAILURE, 0,
1090 _("Cannot specify number of columns when printing in parallel."));
1092 if (parallel_files && print_across_flag)
1093 error (EXIT_FAILURE, 0,
1094 _("Cannot specify both printing across and printing in parallel."));
1096 /* Translate some old short options to new/long options.
1097 To meet downward compatibility with other UNIX pr utilities
1098 and some POSIX specifications. */
1100 if (old_options)
1102 if (old_w)
1104 if (parallel_files || explicit_columns)
1106 /* activate -W */
1107 truncate_lines = TRUE;
1108 if (old_s)
1109 /* adapt HP-UX and SunOS: -s = no separator;
1110 activate -S */
1111 use_col_separator = TRUE;
1113 else
1114 /* old -w sets width with columns only
1115 activate -J */
1116 join_lines = TRUE;
1118 else if (!use_col_separator)
1120 /* No -S option read */
1121 if (old_s && (parallel_files || explicit_columns))
1123 if (!truncate_lines)
1125 /* old -s (without -w and -W) annuls column alignment,
1126 uses fields, activate -J */
1127 join_lines = TRUE;
1128 if (col_sep_length > 0)
1129 /* activate -S */
1130 use_col_separator = TRUE;
1132 else
1133 /* with -W */
1134 /* adapt HP-UX and SunOS: -s = no separator;
1135 activate -S */
1136 use_col_separator = TRUE;
1141 for (; optind < argc; optind++)
1143 file_names[n_files++] = argv[optind];
1146 if (n_files == 0)
1148 /* No file arguments specified; read from standard input. */
1149 print_files (0, NULL);
1151 else
1153 if (parallel_files)
1154 print_files (n_files, file_names);
1155 else
1157 int i;
1158 for (i = 0; i < n_files; i++)
1159 print_files (1, &file_names[i]);
1163 cleanup ();
1165 if (have_read_stdin && fclose (stdin) == EOF)
1166 error (EXIT_FAILURE, errno, _("standard input"));
1167 if (failed_opens > 0)
1168 exit (EXIT_FAILURE);
1169 exit (EXIT_SUCCESS);
1172 /* Parse options of the form -scNNN.
1174 Example: -nck, where 'n' is the option, c is the optional number
1175 separator, and k is the optional width of the field used when printing
1176 a number. */
1178 static void
1179 getoptarg (char *arg, char switch_char, char *character, int *number)
1181 if (!ISDIGIT (*arg))
1182 *character = *arg++;
1183 if (*arg)
1185 long int tmp_long;
1186 if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK
1187 || tmp_long <= 0 || tmp_long > INT_MAX)
1189 error (0, 0,
1190 _("`-%c' extra characters or invalid number in the argument: `%s'"),
1191 switch_char, arg);
1192 usage (2);
1194 *number = (int) tmp_long;
1198 /* Set parameters related to formatting. */
1200 static void
1201 init_parameters (int number_of_files)
1203 int chars_used_by_number = 0;
1205 if (use_form_feed)
1207 lines_per_header = 3;
1208 lines_per_footer = 0;
1211 lines_per_body = lines_per_page - lines_per_header - lines_per_footer;
1212 if (lines_per_body <= 0)
1214 extremities = FALSE;
1215 keep_FF = TRUE;
1217 if (extremities == FALSE)
1218 lines_per_body = lines_per_page;
1220 if (double_space)
1221 lines_per_body = lines_per_body / 2;
1223 /* If input is stdin, cannot print parallel files. BSD dumps core
1224 on this. */
1225 if (number_of_files == 0)
1226 parallel_files = FALSE;
1228 if (parallel_files)
1229 columns = number_of_files;
1231 /* One file, multi columns down: -b option is set to get a consistent
1232 formulation with "FF set by hand" in input files. */
1233 if (storing_columns)
1234 balance_columns = TRUE;
1236 /* Tabification is assumed for multiple columns. */
1237 if (columns > 1)
1239 if (!use_col_separator)
1241 /* Use default separator */
1242 if (join_lines)
1243 col_sep_string = line_separator;
1244 else
1245 col_sep_string = column_separator;
1247 col_sep_length = 1;
1248 use_col_separator = TRUE;
1250 /* It's rather pointless to define a TAB separator with column
1251 alignment */
1252 else if (!join_lines && *col_sep_string == '\t')
1253 col_sep_string = column_separator;
1255 truncate_lines = TRUE;
1256 untabify_input = TRUE;
1257 tabify_output = TRUE;
1259 else
1260 storing_columns = FALSE;
1262 /* -J dominates -w in any case */
1263 if (join_lines)
1264 truncate_lines = FALSE;
1266 if (numbered_lines)
1268 int tmp_i;
1269 int chars_per_default_tab = 8;
1271 line_count = start_line_num;
1273 /* To allow input tab-expansion (-e sensitive) use:
1274 if (number_separator == input_tab_char)
1275 number_width = chars_per_number +
1276 TAB_WIDTH (chars_per_input_tab, chars_per_number); */
1278 /* Estimate chars_per_text without any margin and keep it constant. */
1279 if (number_separator == '\t')
1280 number_width = chars_per_number +
1281 TAB_WIDTH (chars_per_default_tab, chars_per_number);
1282 else
1283 number_width = chars_per_number + 1;
1285 /* The number is part of the column width unless we are
1286 printing files in parallel. */
1287 if (parallel_files)
1288 chars_used_by_number = number_width;
1290 /* We use power_10 to cut off the higher-order digits of the
1291 line_number in function add_line_number */
1292 tmp_i = chars_per_number;
1293 for (power_10 = 1; tmp_i > 0; --tmp_i)
1294 power_10 = 10 * power_10;
1297 chars_per_column = (chars_per_line - chars_used_by_number -
1298 (columns - 1) * col_sep_length) / columns;
1300 if (chars_per_column < 1)
1301 error (EXIT_FAILURE, 0, _("page width too narrow"));
1303 if (numbered_lines)
1305 if (number_buff != NULL)
1306 free (number_buff);
1307 number_buff = (char *) xmalloc (2 * chars_per_number);
1310 /* Pick the maximum between the tab width and the width of an
1311 escape sequence.
1312 The width of an escape sequence (4) isn't the lower limit any longer.
1313 We've to use 8 as the lower limit, if we use chars_per_default_tab = 8
1314 to expand a tab which is not an input_tab-char. */
1315 if (clump_buff != NULL)
1316 free (clump_buff);
1317 clump_buff = (int *) xmalloc ((chars_per_input_tab > 8
1318 ? chars_per_input_tab : 8) * sizeof (int));
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 1 if (number_of_files > 0) and no files can be opened,
1327 0 otherwise.
1329 With each column/file p, p->full_page_printed is initialized,
1330 see also open_file. */
1332 static int
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 if (column_vector != NULLCOL)
1343 free ((char *) column_vector);
1344 column_vector = (COLUMN *) xmalloc (columns * sizeof (COLUMN));
1346 if (parallel_files)
1348 files_left = number_of_files;
1349 for (p = column_vector; files_left--; ++p, ++av)
1351 if (open_file (*av, p) == 0)
1353 --p;
1354 --columns;
1357 if (columns == 0)
1358 return 1;
1359 init_header ("", -1);
1361 else
1363 p = column_vector;
1364 if (number_of_files > 0)
1366 if (open_file (*av, p) == 0)
1367 return 1;
1368 init_header (*av, fileno (p->fp));
1369 p->lines_stored = 0;
1371 else
1373 p->name = _("standard input");
1374 p->fp = stdin;
1375 have_read_stdin = TRUE;
1376 p->status = OPEN;
1377 p->full_page_printed = FALSE;
1378 ++total_files;
1379 init_header ("", -1);
1380 p->lines_stored = 0;
1383 firstname = p->name;
1384 firstfp = p->fp;
1385 for (i = columns - 1, ++p; i; --i, ++p)
1387 p->name = firstname;
1388 p->fp = firstfp;
1389 p->status = OPEN;
1390 p->full_page_printed = FALSE;
1391 p->lines_stored = 0;
1394 files_ready_to_read = total_files;
1395 return 0;
1398 /* Determine print_func and char_func, the functions
1399 used by each column for printing and/or storing.
1401 Determine the horizontal position desired when we begin
1402 printing a column (p->start_position). */
1404 static void
1405 init_funcs (void)
1407 int i, h, h_next;
1408 COLUMN *p;
1410 h = chars_per_margin;
1412 if (!truncate_lines)
1413 h_next = ANYWHERE;
1414 else
1416 /* When numbering lines of parallel files, we enlarge the
1417 first column to accomodate the number. Looks better than
1418 the Sys V approach. */
1419 if (parallel_files && numbered_lines)
1420 h_next = h + chars_per_column + number_width;
1421 else
1422 h_next = h + chars_per_column;
1425 /* Enlarge p->start_position of first column to use the same form of
1426 padding_not_printed with all columns. */
1427 h = h + col_sep_length;
1429 /* This loop takes care of all but the rightmost column. */
1431 for (p = column_vector, i = 1; i < columns; ++p, ++i)
1433 if (storing_columns) /* One file, multi columns down. */
1435 p->char_func = store_char;
1436 p->print_func = print_stored;
1438 else
1439 /* One file, multi columns across; or parallel files. */
1441 p->char_func = print_char;
1442 p->print_func = read_line;
1445 /* Number only the first column when printing files in
1446 parallel. */
1447 p->numbered = numbered_lines && (!parallel_files || i == 1);
1448 p->start_position = h;
1450 /* If we don't truncate lines, all start_positions are
1451 ANYWHERE, except the first column's start_position when
1452 using a margin. */
1454 if (!truncate_lines)
1456 h = ANYWHERE;
1457 h_next = ANYWHERE;
1459 else
1461 h = h_next + col_sep_length;
1462 h_next = h + chars_per_column;
1466 /* The rightmost column.
1468 Doesn't need to be stored unless we intend to balance
1469 columns on the last page. */
1470 if (storing_columns && balance_columns)
1472 p->char_func = store_char;
1473 p->print_func = print_stored;
1475 else
1477 p->char_func = print_char;
1478 p->print_func = read_line;
1481 p->numbered = numbered_lines && (!parallel_files || i == 1);
1482 p->start_position = h;
1485 /* Open a file. Return nonzero if successful, zero if failed.
1487 With each file p, p->full_page_printed is initialized,
1488 see also init_fps. */
1490 static int
1491 open_file (char *name, COLUMN *p)
1493 if (STREQ (name, "-"))
1495 p->name = _("standard input");
1496 p->fp = stdin;
1497 have_read_stdin = 1;
1499 else
1501 p->name = name;
1502 p->fp = fopen (name, "r");
1504 if (p->fp == NULL)
1506 ++failed_opens;
1507 if (!ignore_failed_opens)
1508 error (0, errno, "%s", name);
1509 return 0;
1511 p->status = OPEN;
1512 p->full_page_printed = FALSE;
1513 ++total_files;
1514 return 1;
1517 /* Close the file in P.
1519 If we aren't dealing with multiple files in parallel, we change
1520 the status of all columns in the column list to reflect the close. */
1522 static void
1523 close_file (COLUMN *p)
1525 COLUMN *q;
1526 int i;
1528 if (p->status == CLOSED)
1529 return;
1530 if (ferror (p->fp))
1531 error (EXIT_FAILURE, errno, "%s", p->name);
1532 if (p->fp != stdin && fclose (p->fp) == EOF)
1533 error (EXIT_FAILURE, errno, "%s", p->name);
1535 if (!parallel_files)
1537 for (q = column_vector, i = columns; i; ++q, --i)
1539 q->status = CLOSED;
1540 if (q->lines_stored == 0)
1542 q->lines_to_print = 0;
1546 else
1548 p->status = CLOSED;
1549 p->lines_to_print = 0;
1552 --files_ready_to_read;
1555 /* Put a file on hold until we start a new page,
1556 since we've hit a form feed.
1558 If we aren't dealing with parallel files, we must change the
1559 status of all columns in the column list. */
1561 static void
1562 hold_file (COLUMN *p)
1564 COLUMN *q;
1565 int i;
1567 if (!parallel_files)
1568 for (q = column_vector, i = columns; i; ++q, --i)
1570 if (storing_columns)
1571 q->status = FF_FOUND;
1572 else
1573 q->status = ON_HOLD;
1575 else
1576 p->status = ON_HOLD;
1578 p->lines_to_print = 0;
1579 --files_ready_to_read;
1582 /* Undo hold_file -- go through the column list and change any
1583 ON_HOLD columns to OPEN. Used at the end of each page. */
1585 static void
1586 reset_status (void)
1588 int i = columns;
1589 COLUMN *p;
1591 for (p = column_vector; i; --i, ++p)
1592 if (p->status == ON_HOLD)
1594 p->status = OPEN;
1595 files_ready_to_read++;
1598 if (storing_columns)
1600 if (column_vector->status == CLOSED)
1601 /* We use the info to output an error message in skip_to_page. */
1602 files_ready_to_read = 0;
1603 else
1604 files_ready_to_read = 1;
1608 /* Print a single file, or multiple files in parallel.
1610 Set up the list of columns, opening the necessary files.
1611 Allocate space for storing columns, if necessary.
1612 Skip to first_page_number, if user has asked to skip leading pages.
1613 Determine which functions are appropriate to store/print lines
1614 in each column.
1615 Print the file(s). */
1617 static void
1618 print_files (int number_of_files, char **av)
1620 init_parameters (number_of_files);
1621 if (init_fps (number_of_files, av))
1622 return;
1623 if (storing_columns)
1624 init_store_cols ();
1626 if (first_page_number > 1)
1628 if (!skip_to_page (first_page_number))
1629 return;
1630 else
1631 page_number = first_page_number;
1633 else
1634 page_number = 1;
1636 init_funcs ();
1638 line_number = line_count;
1639 while (print_page ())
1643 /* Initialize header information.
1644 If DESC is non-negative, it is a file descriptor open to
1645 FILENAME for reading. */
1647 static void
1648 init_header (char *filename, int desc)
1650 char *buf;
1651 char initbuf[MAX (256, INT_STRLEN_BOUND (long) + 1)];
1652 struct stat st;
1653 struct tm *tm;
1655 /* If parallel files or standard input, use current date. */
1656 if (STREQ (filename, "-"))
1657 desc = -1;
1658 if (desc < 0 || fstat (desc, &st) != 0)
1659 st.st_mtime = time (NULL);
1661 buf = initbuf;
1662 tm = localtime (&st.st_mtime);
1663 if (! tm)
1664 sprintf (buf, "%ld", (long) st.st_mtime);
1665 else
1667 size_t bufsize = sizeof initbuf;
1668 for (;;)
1670 *buf = '\1';
1671 if (strftime (buf, bufsize, date_format, tm) || ! *buf)
1672 break;
1673 buf = alloca (bufsize *= 2);
1677 if (date_text)
1678 free (date_text);
1679 date_text = xstrdup (buf);
1680 file_text = custom_header ? custom_header : desc < 0 ? "" : filename;
1681 header_width_available = (chars_per_line
1682 - mbswidth (date_text, 0)
1683 - mbswidth (file_text, 0));
1686 /* Set things up for printing a page
1688 Scan through the columns ...
1689 Determine which are ready to print
1690 (i.e., which have lines stored or open files)
1691 Set p->lines_to_print appropriately
1692 (to p->lines_stored if we're storing, or lines_per_body
1693 if we're reading straight from the file)
1694 Keep track of this total so we know when to stop printing */
1696 static void
1697 init_page (void)
1699 int j;
1700 COLUMN *p;
1702 if (storing_columns)
1704 store_columns ();
1705 for (j = columns - 1, p = column_vector; j; --j, ++p)
1707 p->lines_to_print = p->lines_stored;
1710 /* Last column. */
1711 if (balance_columns)
1713 p->lines_to_print = p->lines_stored;
1715 /* Since we're not balancing columns, we don't need to store
1716 the rightmost column. Read it straight from the file. */
1717 else
1719 if (p->status == OPEN)
1721 p->lines_to_print = lines_per_body;
1723 else
1724 p->lines_to_print = 0;
1727 else
1728 for (j = columns, p = column_vector; j; --j, ++p)
1729 if (p->status == OPEN)
1731 p->lines_to_print = lines_per_body;
1733 else
1734 p->lines_to_print = 0;
1737 /* Align empty columns and print separators.
1738 Empty columns will be formed by files with status ON_HOLD or CLOSED
1739 when printing multiple files in parallel. */
1741 static void
1742 align_column (COLUMN *p)
1744 padding_not_printed = p->start_position;
1745 if (padding_not_printed - col_sep_length > 0)
1747 pad_across_to (padding_not_printed - col_sep_length);
1748 padding_not_printed = ANYWHERE;
1751 if (use_col_separator)
1752 print_sep_string ();
1754 if (p->numbered)
1755 add_line_number (p);
1758 /* Print one page.
1760 As long as there are lines left on the page and columns ready to print,
1761 Scan across the column list
1762 if the column has stored lines or the file is open
1763 pad to the appropriate spot
1764 print the column
1765 pad the remainder of the page with \n or \f as requested
1766 reset the status of all files -- any files which where on hold because
1767 of formfeeds are now put back into the lineup. */
1769 static int
1770 print_page (void)
1772 int j;
1773 int lines_left_on_page;
1774 COLUMN *p;
1776 /* Used as an accumulator (with | operator) of successive values of
1777 pad_vertically. The trick is to set pad_vertically
1778 to zero before each run through the inner loop, then after that
1779 loop, it tells us whether a line was actually printed (whether a
1780 newline needs to be output -- or two for double spacing). But those
1781 values have to be accumulated (in pv) so we can invoke pad_down
1782 properly after the outer loop completes. */
1783 int pv;
1785 init_page ();
1787 if (cols_ready_to_print () == 0)
1788 return FALSE;
1790 if (extremities)
1791 print_a_header = TRUE;
1793 /* Don't pad unless we know a page was printed. */
1794 pad_vertically = FALSE;
1795 pv = FALSE;
1797 lines_left_on_page = lines_per_body;
1798 if (double_space)
1799 lines_left_on_page *= 2;
1801 while (lines_left_on_page > 0 && cols_ready_to_print () > 0)
1803 output_position = 0;
1804 spaces_not_printed = 0;
1805 separators_not_printed = 0;
1806 pad_vertically = FALSE;
1807 align_empty_cols = FALSE;
1808 empty_line = TRUE;
1810 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1812 input_position = 0;
1813 if (p->lines_to_print > 0 || p->status == FF_FOUND)
1815 FF_only = FALSE;
1816 padding_not_printed = p->start_position;
1817 if (!(p->print_func) (p))
1818 read_rest_of_line (p);
1819 pv |= pad_vertically;
1821 --p->lines_to_print;
1822 if (p->lines_to_print <= 0)
1824 if (cols_ready_to_print () <= 0)
1825 break;
1828 /* File p changed its status to ON_HOLD or CLOSED */
1829 if (parallel_files && p->status != OPEN)
1831 if (empty_line)
1832 align_empty_cols = TRUE;
1833 else if (p->status == CLOSED ||
1834 (p->status == ON_HOLD && FF_only))
1835 align_column (p);
1838 else if (parallel_files)
1840 /* File status ON_HOLD or CLOSED */
1841 if (empty_line)
1842 align_empty_cols = TRUE;
1843 else
1844 align_column (p);
1847 /* We need it also with an empty column */
1848 if (use_col_separator)
1849 ++separators_not_printed;
1852 if (pad_vertically)
1854 putchar ('\n');
1855 --lines_left_on_page;
1858 if (cols_ready_to_print () <= 0 && !extremities)
1859 break;
1861 if (double_space && pv)
1863 putchar ('\n');
1864 --lines_left_on_page;
1868 if (lines_left_on_page == 0)
1869 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
1870 if (p->status == OPEN)
1871 p->full_page_printed = TRUE;
1873 pad_vertically = pv;
1875 if (pad_vertically && extremities)
1876 pad_down (lines_left_on_page + lines_per_footer);
1877 else if (keep_FF && print_a_FF)
1879 putchar ('\f');
1880 print_a_FF = FALSE;
1883 if (last_page_number && page_number > last_page_number)
1884 return FALSE; /* Stop printing with LAST_PAGE */
1886 reset_status (); /* Change ON_HOLD to OPEN. */
1888 return TRUE; /* More pages to go. */
1891 /* Allocate space for storing columns.
1893 This is necessary when printing multiple columns from a single file.
1894 Lines are stored consecutively in buff, separated by '\0'.
1896 The following doesn't apply any longer - any tuning possible?
1897 (We can't use a fixed offset since with the '-s' flag lines aren't
1898 truncated.)
1900 We maintain a list (line_vector) of pointers to the beginnings
1901 of lines in buff. We allocate one more than the number of lines
1902 because the last entry tells us the index of the last character,
1903 which we need to know in order to print the last line in buff. */
1905 static void
1906 init_store_cols (void)
1908 int total_lines = lines_per_body * columns;
1909 int chars_if_truncate = total_lines * (chars_per_column + 1);
1911 if (line_vector != NULL)
1912 free ((int *) line_vector);
1913 /* FIXME: here's where it was allocated. */
1914 line_vector = (int *) xmalloc ((total_lines + 1) * sizeof (int *));
1916 if (end_vector != NULL)
1917 free ((int *) end_vector);
1918 end_vector = (int *) xmalloc (total_lines * sizeof (int *));
1920 if (buff != NULL)
1921 free (buff);
1922 buff_allocated = (use_col_separator
1923 ? 2 * chars_if_truncate
1924 : chars_if_truncate); /* Tune this. */
1925 buff = (char *) xmalloc (buff_allocated);
1928 /* Store all but the rightmost column.
1929 (Used when printing a single file in multiple downward columns)
1931 For each column
1932 set p->current_line to be the index in line_vector of the
1933 first line in the column
1934 For each line in the column
1935 store the line in buff
1936 add to line_vector the index of the line's first char
1937 buff_start is the index in buff of the first character in the
1938 current line. */
1940 static void
1941 store_columns (void)
1943 int i, j;
1944 int line = 0;
1945 int buff_start;
1946 int last_col; /* The rightmost column which will be saved in buff */
1947 COLUMN *p;
1949 buff_current = 0;
1950 buff_start = 0;
1952 if (balance_columns)
1953 last_col = columns;
1954 else
1955 last_col = columns - 1;
1957 for (i = 1, p = column_vector; i <= last_col; ++i, ++p)
1958 p->lines_stored = 0;
1960 for (i = 1, p = column_vector; i <= last_col && files_ready_to_read;
1961 ++i, ++p)
1963 p->current_line = line;
1964 for (j = lines_per_body; j && files_ready_to_read; --j)
1966 if (p->status == OPEN) /* Redundant. Clean up. */
1968 input_position = 0;
1970 if (!read_line (p))
1971 read_rest_of_line (p);
1973 if (p->status == OPEN
1974 || buff_start != buff_current)
1976 ++p->lines_stored;
1977 line_vector[line] = buff_start;
1978 end_vector[line++] = input_position;
1979 buff_start = buff_current;
1984 /* Keep track of the location of the last char in buff. */
1985 line_vector[line] = buff_start;
1987 if (balance_columns)
1988 balance (line);
1991 static void
1992 balance (int total_stored)
1994 COLUMN *p;
1995 int i, lines;
1996 int first_line = 0;
1998 for (i = 1, p = column_vector; i <= columns; ++i, ++p)
2000 lines = total_stored / columns;
2001 if (i <= total_stored % columns)
2002 ++lines;
2004 p->lines_stored = lines;
2005 p->current_line = first_line;
2007 first_line += lines;
2011 /* Store a character in the buffer. */
2013 static void
2014 store_char (int c)
2016 if (buff_current >= buff_allocated)
2018 /* May be too generous. */
2019 buff_allocated = 2 * buff_allocated;
2020 buff = (char *) xrealloc (buff, buff_allocated * sizeof (char));
2022 buff[buff_current++] = (char) c;
2025 static void
2026 add_line_number (COLUMN *p)
2028 int i;
2029 char *s;
2030 int left_cut;
2032 /* Cutting off the higher-order digits is more informative than
2033 lower-order cut off*/
2034 if (line_number < power_10)
2035 sprintf (number_buff, "%*d", chars_per_number, line_number);
2036 else
2038 left_cut = line_number % power_10;
2039 sprintf (number_buff, "%0*d", chars_per_number, left_cut);
2041 line_number++;
2042 s = number_buff;
2043 for (i = chars_per_number; i > 0; i--)
2044 (p->char_func) ((int) *s++);
2046 if (columns > 1)
2048 /* Tabification is assumed for multiple columns, also for n-separators,
2049 but `default n-separator = TAB' hasn't been given priority over
2050 equal column_width also specified by POSIX. */
2051 if (number_separator == '\t')
2053 i = number_width - chars_per_number;
2054 while (i-- > 0)
2055 (p->char_func) ((int) ' ');
2057 else
2058 (p->char_func) ((int) number_separator);
2060 else
2061 /* To comply with POSIX, we avoid any expansion of default TAB
2062 separator with a single column output. No column_width requirement
2063 has to be considered. */
2065 (p->char_func) ((int) number_separator);
2066 if (number_separator == '\t')
2067 output_position = POS_AFTER_TAB (chars_per_output_tab,
2068 output_position);
2071 if (truncate_lines && !parallel_files)
2072 input_position += number_width;
2075 /* Print (or store) padding until the current horizontal position
2076 is position. */
2078 static void
2079 pad_across_to (int position)
2081 register int h = output_position;
2083 if (tabify_output)
2084 spaces_not_printed = position - output_position;
2085 else
2087 while (++h <= position)
2088 putchar (' ');
2089 output_position = position;
2093 /* Pad to the bottom of the page.
2095 If the user has requested a formfeed, use one.
2096 Otherwise, use newlines. */
2098 static void
2099 pad_down (int lines)
2101 register int i;
2103 if (use_form_feed)
2104 putchar ('\f');
2105 else
2106 for (i = lines; i; --i)
2107 putchar ('\n');
2110 /* Read the rest of the line.
2112 Read from the current column's file until an end of line is
2113 hit. Used when we've truncated a line and we no longer need
2114 to print or store its characters. */
2116 static void
2117 read_rest_of_line (COLUMN *p)
2119 register int c;
2120 FILE *f = p->fp;
2122 while ((c = getc (f)) != '\n')
2124 if (c == '\f')
2126 if ((c = getc (f)) != '\n')
2127 ungetc (c, f);
2128 if (keep_FF)
2129 print_a_FF = TRUE;
2130 hold_file (p);
2131 break;
2133 else if (c == EOF)
2135 close_file (p);
2136 break;
2141 /* Read a line with skip_to_page.
2143 Read from the current column's file until an end of line is
2144 hit. Used when we read full lines to skip pages.
2145 With skip_to_page we have to check for FF-coincidence which is done
2146 in function read_line otherwise.
2147 Count lines of skipped pages to find the line number of 1st page
2148 printed relative to 1st line of input file (start_line_num). */
2150 static void
2151 skip_read (COLUMN *p, int column_number)
2153 register int c;
2154 FILE *f = p->fp;
2155 int i, single_ff = FALSE;
2156 COLUMN *q;
2158 /* Read 1st character in a line or any character succeeding a FF */
2159 if ((c = getc (f)) == '\f' && p->full_page_printed)
2160 /* A FF-coincidence with a previous full_page_printed.
2161 To avoid an additional empty page, eliminate the FF */
2162 if ((c = getc (f)) == '\n')
2163 c = getc (f);
2165 p->full_page_printed = FALSE;
2167 /* 1st character a FF means a single FF without any printable
2168 characters. Don't count it as a line with -n option. */
2169 if (c == '\f')
2170 single_ff = TRUE;
2172 /* Preparing for a FF-coincidence: Maybe we finish that page
2173 without a FF found */
2174 if (last_line)
2175 p->full_page_printed = TRUE;
2177 while (c != '\n')
2179 if (c == '\f')
2181 /* No FF-coincidence possible,
2182 no catching up of a FF-coincidence with next page */
2183 if (last_line)
2185 if (!parallel_files)
2186 for (q = column_vector, i = columns; i; ++q, --i)
2187 q->full_page_printed = FALSE;
2188 else
2189 p->full_page_printed = FALSE;
2192 if ((c = getc (f)) != '\n')
2193 ungetc (c, f);
2194 hold_file (p);
2195 break;
2197 else if (c == EOF)
2199 close_file (p);
2200 break;
2202 c = getc (f);
2205 if (skip_count)
2206 if ((!parallel_files || column_number == 1) && !single_ff)
2207 ++line_count;
2210 /* If we're tabifying output,
2212 When print_char encounters white space it keeps track
2213 of our desired horizontal position and delays printing
2214 until this function is called. */
2216 static void
2217 print_white_space (void)
2219 register int h_new;
2220 register int h_old = output_position;
2221 register int goal = h_old + spaces_not_printed;
2223 while (goal - h_old > 1
2224 && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal)
2226 putchar (output_tab_char);
2227 h_old = h_new;
2229 while (++h_old <= goal)
2230 putchar (' ');
2232 output_position = goal;
2233 spaces_not_printed = 0;
2236 /* Print column separators.
2238 We keep a count until we know that we'll be printing a line,
2239 then print_sep_string() is called. */
2241 static void
2242 print_sep_string ()
2244 char *s;
2245 int l = col_sep_length;
2247 s = col_sep_string;
2249 if (separators_not_printed <= 0)
2251 /* We'll be starting a line with chars_per_margin, anything else? */
2252 if (spaces_not_printed > 0)
2253 print_white_space ();
2255 else
2257 for (; separators_not_printed > 0; --separators_not_printed)
2259 while (l-- > 0)
2261 /* 3 types of sep_strings: spaces only, spaces and chars,
2262 chars only */
2263 if (*s == ' ')
2265 /* We're tabifying output; consecutive spaces in
2266 sep_string may have to be converted to tabs */
2267 s++;
2268 ++spaces_not_printed;
2270 else
2272 if (spaces_not_printed > 0)
2273 print_white_space ();
2274 putchar (*s++);
2275 ++output_position;
2278 /* sep_string ends with some spaces */
2279 if (spaces_not_printed > 0)
2280 print_white_space ();
2285 /* Print (or store, depending on p->char_func) a clump of N
2286 characters. */
2288 static void
2289 print_clump (COLUMN *p, int n, int *clump)
2291 while (n--)
2292 (p->char_func) (*clump++);
2295 /* Print a character.
2297 Update the following comment: process-char hasn't been used any
2298 longer.
2299 If we're tabifying, all tabs have been converted to spaces by
2300 process_char(). Keep a count of consecutive spaces, and when
2301 a nonspace is encountered, call print_white_space() to print the
2302 required number of tabs and spaces. */
2304 static void
2305 print_char (int c)
2307 if (tabify_output)
2309 if (c == ' ')
2311 ++spaces_not_printed;
2312 return;
2314 else if (spaces_not_printed > 0)
2315 print_white_space ();
2317 /* Nonprintables are assumed to have width 0, except '\b'. */
2318 if (!ISPRINT (c))
2320 if (c == '\b')
2321 --output_position;
2323 else
2324 ++output_position;
2326 putchar (c);
2329 /* Skip to page PAGE before printing.
2330 PAGE may be larger than total number of pages. */
2332 static int
2333 skip_to_page (int page)
2335 int n, i, j;
2336 COLUMN *p;
2338 for (n = 1; n < page; ++n)
2340 for (i = 1; i < lines_per_body; ++i)
2342 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2343 if (p->status == OPEN)
2344 skip_read (p, j);
2346 last_line = TRUE;
2347 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2348 if (p->status == OPEN)
2349 skip_read (p, j);
2351 if (storing_columns) /* change FF_FOUND to ON_HOLD */
2352 for (j = 1, p = column_vector; j <= columns; ++j, ++p)
2353 if (p->status != CLOSED)
2354 p->status = ON_HOLD;
2356 reset_status ();
2357 last_line = FALSE;
2359 if (files_ready_to_read < 1)
2361 /* It's very helpful, normally the total number of pages is
2362 not known in advance. */
2363 error (0, 0,
2364 _("starting page number larger than total number of pages: `%d'"),
2366 break;
2369 return files_ready_to_read > 0;
2372 /* Print a header.
2374 Formfeeds are assumed to use up two lines at the beginning of
2375 the page. */
2377 static void
2378 print_header (void)
2380 char page_text[256 + INT_STRLEN_BOUND (int)];
2381 int available_width;
2382 int lhs_spaces;
2383 int rhs_spaces;
2385 if (!use_form_feed)
2386 printf ("\n\n");
2388 output_position = 0;
2389 pad_across_to (chars_per_margin);
2390 print_white_space ();
2392 /* The translator must ensure that formatting the translation of
2393 "Page %d" does not generate more than (sizeof page_text - 1)
2394 bytes. */
2395 sprintf (page_text, _("Page %d"), page_number++);
2396 available_width = header_width_available - mbswidth (page_text, 0);
2397 available_width = MAX (0, available_width);
2398 lhs_spaces = available_width >> 1;
2399 rhs_spaces = available_width - lhs_spaces;
2401 printf ("%s%*s%s%*s%s\n\n\n",
2402 date_text, lhs_spaces, " ", file_text, rhs_spaces, " ", page_text);
2404 print_a_header = FALSE;
2405 output_position = 0;
2408 /* Print (or store, if p->char_func is store_char()) a line.
2410 Read a character to determine whether we have a line or not.
2411 (We may hit EOF, \n, or \f)
2413 Once we know we have a line,
2414 set pad_vertically = TRUE, meaning it's safe
2415 to pad down at the end of the page, since we do have a page.
2416 print a header if needed.
2417 pad across to padding_not_printed if needed.
2418 print any separators which need to be printed.
2419 print a line number if it needs to be printed.
2421 Print the clump which corresponds to the first character.
2423 Enter a loop and keep printing until an end of line condition
2424 exists, or until we exceed chars_per_column.
2426 Return FALSE if we exceed chars_per_column before reading
2427 an end of line character, TRUE otherwise. */
2429 static int
2430 read_line (COLUMN *p)
2432 int c;
2433 int chars IF_LINT (= 0);
2434 int last_input_position;
2435 int j, k;
2436 COLUMN *q;
2438 /* read 1st character in each line or any character succeeding a FF: */
2439 c = getc (p->fp);
2441 last_input_position = input_position;
2443 if (c == '\f' && p->full_page_printed)
2444 if ((c = getc (p->fp)) == '\n')
2445 c = getc (p->fp);
2446 p->full_page_printed = FALSE;
2448 switch (c)
2450 case '\f':
2451 if ((c = getc (p->fp)) != '\n')
2452 ungetc (c, p->fp);
2453 FF_only = TRUE;
2454 if (print_a_header && !storing_columns)
2456 pad_vertically = TRUE;
2457 print_header ();
2459 else if (keep_FF)
2460 print_a_FF = TRUE;
2461 hold_file (p);
2462 return TRUE;
2463 case EOF:
2464 close_file (p);
2465 return TRUE;
2466 case '\n':
2467 break;
2468 default:
2469 chars = char_to_clump (c);
2472 if (truncate_lines && input_position > chars_per_column)
2474 input_position = last_input_position;
2475 return FALSE;
2478 if (p->char_func != store_char)
2480 pad_vertically = TRUE;
2482 if (print_a_header && !storing_columns)
2483 print_header ();
2485 if (parallel_files && align_empty_cols)
2487 /* We have to align empty columns at the beginning of a line. */
2488 k = separators_not_printed;
2489 separators_not_printed = 0;
2490 for (j = 1, q = column_vector; j <= k; ++j, ++q)
2492 align_column (q);
2493 separators_not_printed += 1;
2495 padding_not_printed = p->start_position;
2496 if (truncate_lines)
2497 spaces_not_printed = chars_per_column;
2498 else
2499 spaces_not_printed = 0;
2500 align_empty_cols = FALSE;
2503 if (padding_not_printed - col_sep_length > 0)
2505 pad_across_to (padding_not_printed - col_sep_length);
2506 padding_not_printed = ANYWHERE;
2509 if (use_col_separator)
2510 print_sep_string ();
2513 if (p->numbered)
2514 add_line_number (p);
2516 empty_line = FALSE;
2517 if (c == '\n')
2518 return TRUE;
2520 print_clump (p, chars, clump_buff);
2522 for (;;)
2524 c = getc (p->fp);
2526 switch (c)
2528 case '\n':
2529 return TRUE;
2530 case '\f':
2531 if ((c = getc (p->fp)) != '\n')
2532 ungetc (c, p->fp);
2533 if (keep_FF)
2534 print_a_FF = TRUE;
2535 hold_file (p);
2536 return TRUE;
2537 case EOF:
2538 close_file (p);
2539 return TRUE;
2542 last_input_position = input_position;
2543 chars = char_to_clump (c);
2544 if (truncate_lines && input_position > chars_per_column)
2546 input_position = last_input_position;
2547 return FALSE;
2550 print_clump (p, chars, clump_buff);
2554 /* Print a line from buff.
2556 If this function has been called, we know we have "something to
2557 print". But it remains to be seen whether we have a real text page
2558 or an empty page (a single form feed) with/without a header only.
2559 Therefore first we set pad_vertically to TRUE and print a header
2560 if necessary.
2561 If FF_FOUND and we are using -t|-T option we omit any newline by
2562 setting pad_vertically to FALSE (see print_page).
2563 Otherwise we pad across if necessary, print separators if necessary
2564 and text of COLUMN *p.
2566 Return TRUE, meaning there is no need to call read_rest_of_line. */
2568 static int
2569 print_stored (COLUMN *p)
2571 COLUMN *q;
2572 int i;
2574 int line = p->current_line++;
2575 register char *first = &buff[line_vector[line]];
2576 /* FIXME
2577 UMR: Uninitialized memory read:
2578 * This is occurring while in:
2579 print_stored [pr.c:2239]
2580 * Reading 4 bytes from 0x5148c in the heap.
2581 * Address 0x5148c is 4 bytes into a malloc'd block at 0x51488 of 676 bytes
2582 * This block was allocated from:
2583 malloc [rtlib.o]
2584 xmalloc [xmalloc.c:94]
2585 init_store_cols [pr.c:1648]
2587 register char *last = &buff[line_vector[line + 1]];
2589 pad_vertically = TRUE;
2591 if (print_a_header)
2592 print_header ();
2594 if (p->status == FF_FOUND)
2596 for (i = 1, q = column_vector; i <= columns; ++i, ++q)
2597 q->status = ON_HOLD;
2598 if (column_vector->lines_to_print <= 0)
2600 if (!extremities)
2601 pad_vertically = FALSE;
2602 return TRUE; /* print a header only */
2606 if (padding_not_printed - col_sep_length > 0)
2608 pad_across_to (padding_not_printed - col_sep_length);
2609 padding_not_printed = ANYWHERE;
2612 if (use_col_separator)
2613 print_sep_string ();
2615 while (first != last)
2616 print_char (*first++);
2618 if (spaces_not_printed == 0)
2620 output_position = p->start_position + end_vector[line];
2621 if (p->start_position - col_sep_length == chars_per_margin)
2622 output_position -= col_sep_length;
2625 return TRUE;
2628 /* Convert a character to the proper format and return the number of
2629 characters in the resulting clump. Increment input_position by
2630 the width of the clump.
2632 Tabs are converted to clumps of spaces.
2633 Nonprintable characters may be converted to clumps of escape
2634 sequences or control prefixes.
2636 Note: the width of a clump is not necessarily equal to the number of
2637 characters in clump_buff. (e.g, the width of '\b' is -1, while the
2638 number of characters is 1.) */
2640 static int
2641 char_to_clump (int c)
2643 register int *s = clump_buff;
2644 register int i;
2645 char esc_buff[4];
2646 int width;
2647 int chars;
2648 int chars_per_c = 8;
2650 if (c == input_tab_char)
2651 chars_per_c = chars_per_input_tab;
2653 if (c == input_tab_char || c == '\t')
2655 width = TAB_WIDTH (chars_per_c, input_position);
2657 if (untabify_input)
2659 for (i = width; i; --i)
2660 *s++ = ' ';
2661 chars = width;
2663 else
2665 *s = c;
2666 chars = 1;
2670 else if (!ISPRINT (c))
2672 if (use_esc_sequence)
2674 width = 4;
2675 chars = 4;
2676 *s++ = '\\';
2677 sprintf (esc_buff, "%03o", c);
2678 for (i = 0; i <= 2; ++i)
2679 *s++ = (int) esc_buff[i];
2681 else if (use_cntrl_prefix)
2683 if (c < 0200)
2685 width = 2;
2686 chars = 2;
2687 *s++ = '^';
2688 *s++ = c ^ 0100;
2690 else
2692 width = 4;
2693 chars = 4;
2694 *s++ = '\\';
2695 sprintf (esc_buff, "%03o", c);
2696 for (i = 0; i <= 2; ++i)
2697 *s++ = (int) esc_buff[i];
2700 else if (c == '\b')
2702 width = -1;
2703 chars = 1;
2704 *s = c;
2706 else
2708 width = 0;
2709 chars = 1;
2710 *s = c;
2713 else
2715 width = 1;
2716 chars = 1;
2717 *s = c;
2720 input_position += width;
2721 return chars;
2724 /* We've just printed some files and need to clean up things before
2725 looking for more options and printing the next batch of files.
2727 Free everything we've xmalloc'ed, except `header'. */
2729 static void
2730 cleanup (void)
2732 if (number_buff)
2733 free (number_buff);
2734 if (clump_buff)
2735 free (clump_buff);
2736 if (column_vector)
2737 free (column_vector);
2738 if (line_vector)
2739 free (line_vector);
2740 if (end_vector)
2741 free (end_vector);
2742 if (buff)
2743 free (buff);
2746 /* Complain, print a usage message, and die. */
2748 void
2749 usage (int status)
2751 if (status != 0)
2752 fprintf (stderr, _("Try `%s --help' for more information.\n"),
2753 program_name);
2754 else
2756 printf (_("\
2757 Usage: %s [OPTION]... [FILE]...\n\
2759 program_name);
2761 fputs (_("\
2762 Paginate or columnate FILE(s) for printing.\n\
2764 "), stdout);
2765 fputs (_("\
2766 Mandatory arguments to long options are mandatory for short options too.\n\
2767 "), stdout);
2768 fputs (_("\
2769 +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]\n\
2770 begin [stop] printing with page FIRST_[LAST_]PAGE\n\
2771 -COLUMN, --columns=COLUMN\n\
2772 produce COLUMN-column output and print columns down,\n\
2773 unless -a is used. Balance number of lines in the\n\
2774 columns on each page.\n\
2775 "), stdout);
2776 fputs (_("\
2777 -a, --across print columns across rather than down, used together\n\
2778 with -COLUMN\n\
2779 -c, --show-control-chars\n\
2780 use hat notation (^G) and octal backslash notation\n\
2781 -d, --double-space\n\
2782 double space the output\n\
2783 "), stdout);
2784 fputs (_("\
2785 -D, --date-format=FORMAT\n\
2786 use FORMAT for the header date\n\
2787 -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]\n\
2788 expand input CHARs (TABs) to tab WIDTH (8)\n\
2789 -F, -f, --form-feed\n\
2790 use form feeds instead of newlines to separate pages\n\
2791 (by a 3-line page header with -F or a 5-line header\n\
2792 and trailer without -F)\n\
2793 "), stdout);
2794 fputs (_("\
2795 -h HEADER, --header=HEADER\n\
2796 use a centered HEADER instead of filename in page header,\n\
2797 -h \"\" prints a blank line, don't use -h\"\"\n\
2798 -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]\n\
2799 replace spaces with CHARs (TABs) to tab WIDTH (8)\n\
2800 -J, --join-lines merge full lines, turns off -W line truncation, no column\n\
2801 alignment, --sep-string[=STRING] sets separators\n\
2802 "), stdout);
2803 fputs (_("\
2804 -l PAGE_LENGTH, --length=PAGE_LENGTH\n\
2805 set the page length to PAGE_LENGTH (66) lines\n\
2806 (default number of lines of text 56, and with -F 63)\n\
2807 -m, --merge print all files in parallel, one in each column,\n\
2808 truncate lines, but join lines of full length with -J\n\
2809 "), stdout);
2810 fputs (_("\
2811 -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]\n\
2812 number lines, use DIGITS (5) digits, then SEP (TAB),\n\
2813 default counting starts with 1st line of input file\n\
2814 -N NUMBER, --first-line-number=NUMBER\n\
2815 start counting with NUMBER at 1st line of first\n\
2816 page printed (see +FIRST_PAGE)\n\
2817 "), stdout);
2818 fputs (_("\
2819 -o MARGIN, --indent=MARGIN\n\
2820 offset each line with MARGIN (zero) spaces, do not\n\
2821 affect -w or -W, MARGIN will be added to PAGE_WIDTH\n\
2822 -r, --no-file-warnings\n\
2823 omit warning when a file cannot be opened\n\
2824 "), stdout);
2825 fputs (_("\
2826 -s[CHAR],--separator[=CHAR]\n\
2827 separate columns by a single character, default for CHAR\n\
2828 is the <TAB> character without -w and \'no char\' with -w\n\
2829 -s[CHAR] turns off line truncation of all 3 column\n\
2830 options (-COLUMN|-a -COLUMN|-m) except -w is set\n\
2831 "), stdout);
2832 fputs (_("\
2833 -SSTRING, --sep-string[=STRING]\n\
2834 "), stdout);
2835 fputs (_("\
2836 separate columns by STRING,\n\
2837 without -S: Default separator <TAB> with -J and <space>\n\
2838 otherwise (same as -S\" \"), no effect on column options\n\
2839 -t, --omit-header omit page headers and trailers\n\
2840 "), stdout);
2841 fputs (_("\
2842 -T, --omit-pagination\n\
2843 omit page headers and trailers, eliminate any pagination\n\
2844 by form feeds set in input files\n\
2845 -v, --show-nonprinting\n\
2846 use octal backslash notation\n\
2847 -w PAGE_WIDTH, --width=PAGE_WIDTH\n\
2848 set page width to PAGE_WIDTH (72) characters for\n\
2849 multiple text-column output only, -s[char] turns off (72)\n\
2850 "), stdout);
2851 fputs (_("\
2852 -W PAGE_WIDTH, --page-width=PAGE_WIDTH\n\
2853 set page width to PAGE_WIDTH (72) characters always,\n\
2854 truncate lines, except -J option is set, no interference\n\
2855 with -S or -s\n\
2856 "), stdout);
2857 fputs (HELP_OPTION_DESCRIPTION, stdout);
2858 fputs (VERSION_OPTION_DESCRIPTION, stdout);
2859 fputs (_("\
2861 -T implied by -l nn when nn <= 10 or <= 3 with -F. With no FILE, or when\n\
2862 FILE is -, read standard input.\n\
2863 "), stdout);
2864 printf (_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
2866 exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);