forked from coreutils/coreutils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpr.c
2848 lines (2417 loc) · 84.7 KB
/
pr.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* pr -- convert text files for printing.
Copyright (C) 1988-2020 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. */
/* By Pete TerMaat, with considerable refinement by Roland Huebner. */
/* Things to watch: Sys V screws up on ...
pr -n -3 -s: /usr/dict/words
pr -m -o10 -n /usr/dict/words{,,,}
pr -6 -a -n -o5 /usr/dict/words
Ideas:
Keep a things_to_do list of functions to call when we know we have
something to print. Cleaner than current series of checks.
Improve the printing of control prefixes.
Expand the file name in the centered header line to a full file name.
Concept:
If the input_tab_char differs from the default value TAB
('-e[CHAR[...]]' is used), any input text tab is expanded to the
default width of 8 spaces (compare char_to_clump). - Same as SunOS
does.
The treatment of the number_separator (compare add_line_number):
The default value TAB of the number_separator ('-n[SEP[...]]') doesn't
be thought to be an input character. An optional '-e'-input has no
effect.
- With single column output
only one POSIX requirement has to be met:
The default n-separator should be a TAB. The consequence is a
different width between the number and the text if the output position
of the separator changes, i.e., it depends upon the left margin used.
That's not nice but easy-to-use together with the defaults of other
utilities, e.g. sort or cut. - Same as SunOS does.
- With multicolumn output
two conflicting POSIX requirements exist:
First "default n-separator is TAB", second "output text columns shall
be of equal width". Moreover POSIX specifies the number+separator a
part of the column, together with '-COLUMN' and '-a -COLUMN'.
(With -m output the number shall occupy each line only once. Exactly
the same situation as single column output exists.)
GNU pr gives priority to the 2nd requirement and observes POSIX
column definition. The n-separator TAB is expanded to the same number
of spaces in each column using the default value 8. Tabification is
only performed if it is compatible with the output position.
Consequence: The output text columns are of equal width. The layout
of a page does not change if the left margin varies. - Looks better
than the SunOS approach.
SunOS pr gives priority to the 1st requirement. n-separator TAB
width varies with each column. Only the width of text part of the
column is fixed.
Consequence: The output text columns don't have equal width. The
widths and the layout of the whole page varies with the left margin.
An overflow of the line length (without margin) over the input value
PAGE_WIDTH may occur.
The interference of the POSIX-compliant small letter options -w and -s:
("interference" means "setting a _separator_ with -s switches off the
column structure and the default - not generally - page_width,
acts on -w option")
options: text form / separator: equivalent new options:
-w l -s[x]
--------------------------------------------------------------------
1. -- -- columns / space --
trunc. to page_width = 72
2. -- -s[:] full lines / TAB[:] -J --sep-string[="<TAB>"|:]
no truncation
3. -w l -- columns / space -W l
trunc. to page_width = l
4. -w l -s[:] columns / no sep.[:] -W l --sep-string[=:]
trunc. to page_width = l
--------------------------------------------------------------------
Options:
Including version 1.22i:
Some SMALL LETTER options have been redefined with the object of a
better POSIX compliance. The output of some further cases has been
adapted to other UNIXes. A violation of downward compatibility has to
be accepted.
Some NEW CAPITAL LETTER options ( -J, -S, -W) has been introduced to
turn off unexpected interferences of small letter options (-s and -w
together with the three column options).
-N option and the second argument LAST_PAGE of +FIRST_PAGE offer more
flexibility; The detailed handling of form feeds set in the input
files requires -T option.
Capital letter options dominate small letter ones.
Some of the option-arguments cannot be specified as separate arguments
from the preceding option letter (already stated in POSIX specification).
Form feeds in the input cause page breaks in the output. Multiple
form feeds produce empty pages.
+FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE]
begin [stop] printing with page FIRST_[LAST_]PAGE
-COLUMN, --columns=COLUMN
Produce output that is COLUMN columns wide and
print columns down, unless -a is used. Balance number of
lines in the columns on each page.
-a, --across Print columns across rather than down, used
together with -COLUMN. The input
one
two
three
four
will be printed with '-a -3' as
one two three
four
-b Balance columns on the last page.
-b is no longer an independent option. It's always used
together with -COLUMN (unless -a is used) to get a
consistent formulation with "FF set by hand" in input
files. Each formfeed found terminates the number of lines
to be read with the actual page. The situation for
printing columns down is equivalent to that on the last
page. So we need a balancing.
Keeping -b as an underground option guarantees some
downward compatibility. Utilities using pr with -b
(a most frequently used form) still work as usual.
-c, --show-control-chars
Print unprintable characters as control prefixes.
Control-g is printed as ^G (use hat notation) and
octal backslash notation.
-d, --double-space Double space the output.
-D FORMAT, --date-format=FORMAT Use FORMAT for the header date.
-e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]]
Expand tabs to spaces on input. Optional argument CHAR
is the input TAB character. (Default is TAB). Optional
argument WIDTH is the input TAB character's width.
(Default is 8.)
-F, -f, --form-feed Use formfeeds instead of newlines to separate
pages. A three line HEADER is used, no TRAILER with -F,
without -F both HEADER and TRAILER are made of five lines.
-h HEADER, --header=HEADER
Replace the filename in the header with the string HEADER.
A centered header is used.
-i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]]
Replace spaces with tabs on output. Optional argument
CHAR is the output TAB character. (Default is TAB).
Optional argument WIDTH is the output TAB character's
width. (Default is 8)
-J, --join-lines Merge lines of full length, turns off -W/-w
line truncation, no column alignment, --sep-string[=STRING]
sets separators, works with all column options
(-COLUMN | -a -COLUMN | -m).
-J has been introduced (together with -W and --sep-string) to
disentangle the old (POSIX compliant) options -w, -s
along with the 3 column options.
-l PAGE_LENGTH, --length=PAGE_LENGTH
Set the page length to PAGE_LENGTH lines. Default is 66,
including 5 lines of HEADER and 5 lines of TRAILER
without -F, but only 3 lines of HEADER and no TRAILER
with -F (i.e the number of text lines defaults to 56 or
63 respectively).
-m, --merge Print files in parallel; pad_across_to align
columns; truncate lines and print separator strings;
Do it also with empty columns to get a continuous line
numbering and column marking by separators throughout
the whole merged file.
Empty pages in some input files produce empty columns
[marked by separators] in the merged pages. Completely
empty merged pages show no column separators at all.
The layout of a merged page is ruled by the largest form
feed distance of the single pages at that page. Shorter
columns will be filled up with empty lines.
Together with -J option join lines of full length and
set separators when -S option is used.
-n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]]
Provide DIGITS digit line numbering (default for DIGITS
is 5). With multicolumn output the number occupies the
first DIGITS column positions of each text column or only
each line of -m output.
With single column output the number precedes each line
just as -m output.
Optional argument SEP is the character appended to the
line number to separate it from the text followed.
The default separator is a TAB. In a strict sense a TAB
is always printed with single column output only. The
TAB-width varies with the TAB-position, e.g. with the
left margin specified by -o option.
With multicolumn output priority is given to "equal width
of output columns" (a POSIX specification). The TAB-width
is fixed to the value of the 1st column and does not
change with different values of left margin. That means a
fixed number of spaces is always printed in the place of
a TAB. The tabification depends upon the output
position.
Default counting of the line numbers starts with 1st
line of the input file (not the 1st line printed,
compare the --page option and -N option).
-N NUMBER, --first-line-number=NUMBER
Start line counting with the number NUMBER at the 1st
line of first page printed (mostly not the 1st line of
the input file).
-o MARGIN, --indent=MARGIN
Offset each line with a margin MARGIN spaces wide.
Total page width is the size of the margin plus the
PAGE_WIDTH set with -W/-w option.
-r, --no-file-warnings
Omit warning when a file cannot be opened.
-s[CHAR], --separator[=CHAR]
Separate columns by a single character CHAR, default for
CHAR is the TAB character without -w and 'no char' with -w.
Without '-s' default separator 'space' is set.
-s[CHAR] turns off line truncation of all 3 column options
(-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX
compliant formulation. The source code translates -s into
the new options -S and -J, also -W if required.
-S[STRING], --sep-string[=STRING]
Separate columns by any string STRING. The -S option
doesn't react upon the -W/-w option (unlike -s option
does). It defines a separator nothing else.
Without -S: Default separator TAB is used with -J and
'space' otherwise (same as -S" ").
With -S "": No separator is used.
Quotes should be used with blanks and some shell active
characters.
-S is problematic because in its obsolete form you
cannot use -S "STRING", but in its standard form you
must use -S "STRING" if STRING is empty. Use
--sep-string to avoid the ambiguity.
-t, --omit-header Do not print headers or footers but retain form
feeds set in the input files.
-T, --omit-pagination
Do not print headers or footers, eliminate any pagination
by form feeds set in the input files.
-v, --show-nonprinting
Print unprintable characters as escape sequences. Use
octal backslash notation. Control-G becomes \007.
-w PAGE_WIDTH, --width=PAGE_WIDTH
Set page width to PAGE_WIDTH characters for multiple
text-column output only (default for PAGE_WIDTH is 72).
-s[CHAR] turns off the default page width and any line
truncation. Lines of full length will be merged,
regardless of the column options set. A POSIX compliant
formulation.
-W PAGE_WIDTH, --page-width=PAGE_WIDTH
Set the page width to PAGE_WIDTH characters. That's valid
with and without a column option. Text lines will be
truncated, unless -J is used. Together with one of the
column options (-COLUMN| -a -COLUMN| -m) column alignment
is always used.
Default is 72 characters.
Without -W PAGE_WIDTH
- but with one of the column options default truncation of
72 characters is used (to keep downward compatibility
and to simplify most frequently met column tasks).
Column alignment and column separators are used.
- and without any of the column options NO line truncation
is used (to keep downward compatibility and to meet most
frequent tasks). That's equivalent to -W 72 -J .
With/without -W PAGE_WIDTH the header line is always
truncated to avoid line overflow.
(In pr versions newer than 1.14 -S option does no longer
affect -W option.)
*/
#include <config.h>
#include <getopt.h>
#include <sys/types.h>
#include "system.h"
#include "die.h"
#include "error.h"
#include "fadvise.h"
#include "hard-locale.h"
#include "mbswidth.h"
#include "quote.h"
#include "stat-time.h"
#include "stdio--.h"
#include "strftime.h"
#include "xstrtol.h"
#include "xstrtol-error.h"
#include "xdectoint.h"
/* The official name of this program (e.g., no 'g' prefix). */
#define PROGRAM_NAME "pr"
#define AUTHORS \
proper_name ("Pete TerMaat"), \
proper_name ("Roland Huebner")
/* Used with start_position in the struct COLUMN described below.
If start_position == ANYWHERE, we aren't truncating columns and
can begin printing a column anywhere. Otherwise we must pad to
the horizontal position start_position. */
#define ANYWHERE 0
/* Each column has one of these structures allocated for it.
If we're only dealing with one file, fp is the same for all
columns.
The general strategy is to spend time setting up these column
structures (storing columns if necessary), after which printing
is a matter of flitting from column to column and calling
print_func.
Parallel files, single files printing across in multiple
columns, and single files printing down in multiple columns all
fit the same printing loop.
print_func Function used to print lines in this column.
If we're storing this column it will be
print_stored(), Otherwise it will be read_line().
char_func Function used to process characters in this column.
If we're storing this column it will be store_char(),
otherwise it will be print_char().
current_line Index of the current entry in line_vector, which
contains the index of the first character of the
current line in buff[].
lines_stored Number of lines in this column which are stored in
buff.
lines_to_print If we're storing this column, lines_to_print is
the number of stored_lines which remain to be
printed. Otherwise it is the number of lines
we can print without exceeding lines_per_body.
start_position The horizontal position we want to be in before we
print the first character in this column.
numbered True means precede this column with a line number. */
/* FIXME: There are many unchecked integer overflows in this file,
that will cause this command to misbehave given large inputs or
options. Many of the "int" values below should be "size_t" or
something else like that. */
struct COLUMN;
struct COLUMN
{
FILE *fp; /* Input stream for this column. */
char const *name; /* File name. */
enum
{
OPEN,
FF_FOUND, /* used with -b option, set with \f, changed
to ON_HOLD after print_header */
ON_HOLD, /* Hit a form feed. */
CLOSED
}
status; /* Status of the file pointer. */
/* Func to print lines in this col. */
bool (*print_func) (struct COLUMN *);
/* Func to print/store chars in this col. */
void (*char_func) (char);
int current_line; /* Index of current place in line_vector. */
int lines_stored; /* Number of lines stored in buff. */
int lines_to_print; /* No. lines stored or space left on page. */
int start_position; /* Horizontal position of first char. */
bool numbered;
bool full_page_printed; /* True means printed without a FF found. */
/* p->full_page_printed controls a special case of "FF set by hand":
True means a full page has been printed without FF found. To avoid an
additional empty page we have to ignore a FF immediately following in
the next line. */
};
typedef struct COLUMN COLUMN;
static int char_to_clump (char c);
static bool read_line (COLUMN *p);
static bool print_page (void);
static bool print_stored (COLUMN *p);
static bool open_file (char *name, COLUMN *p);
static bool skip_to_page (uintmax_t page);
static void print_header (void);
static void pad_across_to (int position);
static void add_line_number (COLUMN *p);
static void getoptnum (const char *n_str, int min, int *num,
const char *errfmt);
static void getoptarg (char *arg, char switch_char, char *character,
int *number);
static void print_files (int number_of_files, char **av);
static void init_parameters (int number_of_files);
static void init_header (char const *filename, int desc);
static bool init_fps (int number_of_files, char **av);
static void init_funcs (void);
static void init_store_cols (void);
static void store_columns (void);
static void balance (int total_stored);
static void store_char (char c);
static void pad_down (unsigned int lines);
static void read_rest_of_line (COLUMN *p);
static void skip_read (COLUMN *p, int column_number);
static void print_char (char c);
static void cleanup (void);
static void print_sep_string (void);
static void separator_string (const char *optarg_S);
/* All of the columns to print. */
static COLUMN *column_vector;
/* When printing a single file in multiple downward columns,
we store the leftmost columns contiguously in buff.
To print a line from buff, get the index of the first character
from line_vector[i], and print up to line_vector[i + 1]. */
static char *buff;
/* Index of the position in buff where the next character
will be stored. */
static unsigned int buff_current;
/* The number of characters in buff.
Used for allocation of buff and to detect overflow of buff. */
static size_t buff_allocated;
/* Array of indices into buff.
Each entry is an index of the first character of a line.
This is used when storing lines to facilitate shuffling when
we do column balancing on the last page. */
static int *line_vector;
/* Array of horizontal positions.
For each line in line_vector, end_vector[line] is the horizontal
position we are in after printing that line. We keep track of this
so that we know how much we need to pad to prepare for the next
column. */
static int *end_vector;
/* (-m) True means we're printing multiple files in parallel. */
static bool parallel_files = false;
/* (-m) True means a line starts with some empty columns (some files
already CLOSED or ON_HOLD) which we have to align. */
static bool align_empty_cols;
/* (-m) True means we have not yet found any printable column in a line.
align_empty_cols = true has to be maintained. */
static bool empty_line;
/* (-m) False means printable column output precedes a form feed found.
Column alignment is done only once. No additional action with that form
feed.
True means we found only a form feed in a column. Maybe we have to do
some column alignment with that form feed. */
static bool FF_only;
/* (-[0-9]+) True means we're given an option explicitly specifying
number of columns. Used to detect when this option is used with -m
and when translating old options to new/long options. */
static bool explicit_columns = false;
/* (-t|-T) False means we aren't printing headers and footers. */
static bool extremities = true;
/* (-t) True means we retain all FF set by hand in input files.
False is set with -T option. */
static bool keep_FF = false;
static bool print_a_FF = false;
/* True means we need to print a header as soon as we know we've got input
to print after it. */
static bool print_a_header;
/* (-f) True means use formfeeds instead of newlines to separate pages. */
static bool use_form_feed = false;
/* True means we have read the standard input. */
static bool have_read_stdin = false;
/* True means the -a flag has been given. */
static bool print_across_flag = false;
/* True means we're printing one file in multiple (>1) downward columns. */
static bool storing_columns = true;
/* (-b) True means balance columns on the last page as Sys V does. */
/* That's no longer an independent option. With storing_columns = true
balance_columns = true is used too (s. function init_parameters).
We get a consistent formulation with "FF set by hand" in input files. */
static bool balance_columns = false;
/* (-l) Number of lines on a page, including header and footer lines. */
static int lines_per_page = 66;
/* Number of lines in the header and footer can be reset to 0 using
the -t flag. */
enum { lines_per_header = 5 };
static int lines_per_body;
enum { lines_per_footer = 5 };
/* (-w|-W) Width in characters of the page. Does not include the width of
the margin. */
static int chars_per_line = 72;
/* (-w|W) True means we truncate lines longer than chars_per_column. */
static bool truncate_lines = false;
/* (-J) True means we join lines without any line truncation. -J
dominates -w option. */
static bool join_lines = false;
/* Number of characters in a column. Based on col_sep_length and
page width. */
static int chars_per_column;
/* (-e) True means convert tabs to spaces on input. */
static bool untabify_input = false;
/* (-e) The input tab character. */
static char input_tab_char = '\t';
/* (-e) Tabstops are at chars_per_tab, 2*chars_per_tab, 3*chars_per_tab, ...
where the leftmost column is 1. */
static int chars_per_input_tab = 8;
/* (-i) True means convert spaces to tabs on output. */
static bool tabify_output = false;
/* (-i) The output tab character. */
static char output_tab_char = '\t';
/* (-i) The width of the output tab. */
static int chars_per_output_tab = 8;
/* Keeps track of pending white space. When we hit a nonspace
character after some whitespace, we print whitespace, tabbing
if necessary to get to output_position + spaces_not_printed. */
static int spaces_not_printed;
/* (-o) Number of spaces in the left margin (tabs used when possible). */
static int chars_per_margin = 0;
/* Position where the next character will fall.
Leftmost position is 0 + chars_per_margin.
Rightmost position is chars_per_margin + chars_per_line - 1.
This is important for converting spaces to tabs on output. */
static int output_position;
/* Horizontal position relative to the current file.
(output_position depends on where we are on the page;
input_position depends on where we are in the file.)
Important for converting tabs to spaces on input. */
static int input_position;
/* True if there were any failed opens so we can exit with nonzero
status. */
static bool failed_opens = false;
/* The number of spaces taken up if we print a tab character with width
c_ from position h_. */
#define TAB_WIDTH(c_, h_) ((c_) - ((h_) % (c_)))
/* The horizontal position we'll be at after printing a tab character
of width c_ from the position h_. */
#define POS_AFTER_TAB(c_, h_) ((h_) + TAB_WIDTH (c_, h_))
/* (-NNN) Number of columns of text to print. */
static int columns = 1;
/* (+NNN:MMM) Page numbers on which to begin and stop printing.
first_page_number = 0 will be used to check input only. */
static uintmax_t first_page_number = 0;
static uintmax_t last_page_number = UINTMAX_MAX;
/* Number of files open (not closed, not on hold). */
static int files_ready_to_read = 0;
/* Current page number. Displayed in header. */
static uintmax_t page_number;
/* Current line number. Displayed when -n flag is specified.
When printing files in parallel (-m flag), line numbering is as follows:
1 foo goo moo
2 hoo too zoo
When printing files across (-a flag), ...
1 foo 2 moo 3 goo
4 hoo 5 too 6 zoo
Otherwise, line numbering is as follows:
1 foo 3 goo 5 too
2 moo 4 hoo 6 zoo */
static int line_number;
/* (-n) True means lines should be preceded by numbers. */
static bool numbered_lines = false;
/* (-n) Character which follows each line number. */
static char number_separator = '\t';
/* (-n) line counting starts with 1st line of input file (not with 1st
line of 1st page printed). */
static int line_count = 1;
/* (-n) True means counting of skipped lines starts with 1st line of
input file. False means -N option is used in addition, counting of
skipped lines not required. */
static bool skip_count = true;
/* (-N) Counting starts with start_line_number = NUMBER at 1st line of
first page printed, usually not 1st page of input file. */
static int start_line_num = 1;
/* (-n) Width in characters of a line number. */
static int chars_per_number = 5;
/* Used when widening the first column to accommodate numbers -- only
needed when printing files in parallel. Includes width of both the
number and the number_separator. */
static int number_width;
/* Buffer sprintf uses to format a line number. */
static char *number_buff;
/* (-v) True means unprintable characters are printed as escape sequences.
control-g becomes \007. */
static bool use_esc_sequence = false;
/* (-c) True means unprintable characters are printed as control prefixes.
control-g becomes ^G. */
static bool use_cntrl_prefix = false;
/* (-d) True means output is double spaced. */
static bool double_space = false;
/* Number of files opened initially in init_files. Should be 1
unless we're printing multiple files in parallel. */
static int total_files = 0;
/* (-r) True means don't complain if we can't open a file. */
static bool ignore_failed_opens = false;
/* (-S) True means we separate columns with a specified string.
-S option does not affect line truncation nor column alignment. */
static bool use_col_separator = false;
/* String used to separate columns if the -S option has been specified.
Default without -S but together with one of the column options
-a|COLUMN|-m is a 'space' and with the -J option a 'tab'. */
static char const *col_sep_string = "";
static int col_sep_length = 0;
static char *column_separator = (char *) " ";
static char *line_separator = (char *) "\t";
/* Number of separator characters waiting to be printed as soon as we
know that we have any input remaining to be printed. */
static int separators_not_printed;
/* Position we need to pad to, as soon as we know that we have input
remaining to be printed. */
static int padding_not_printed;
/* True means we should pad the end of the page. Remains false until we
know we have a page to print. */
static bool pad_vertically;
/* (-h) String of characters used in place of the filename in the header. */
static char *custom_header;
/* (-D) Date format for the header. */
static char const *date_format;
/* The local time zone rules, as per the TZ environment variable. */
static timezone_t localtz;
/* Date and file name for the header. */
static char *date_text;
static char const *file_text;
/* Output columns available, not counting the date and file name. */
static int header_width_available;
static char *clump_buff;
/* True means we read the line no. lines_per_body in skip_read
called by skip_to_page. That variable controls the coincidence of a
"FF set by hand" and "full_page_printed", see above the definition of
structure COLUMN. */
static bool last_line = false;
/* For long options that have no equivalent short option, use a
non-character as a pseudo short option, starting with CHAR_MAX + 1. */
enum
{
COLUMNS_OPTION = CHAR_MAX + 1,
PAGES_OPTION
};
static char const short_options[] =
"-0123456789D:FJN:S::TW:abcde::fh:i::l:mn::o:rs::tvw:";
static struct option const long_options[] =
{
{"pages", required_argument, NULL, PAGES_OPTION},
{"columns", required_argument, NULL, COLUMNS_OPTION},
{"across", no_argument, NULL, 'a'},
{"show-control-chars", no_argument, NULL, 'c'},
{"double-space", no_argument, NULL, 'd'},
{"date-format", required_argument, NULL, 'D'},
{"expand-tabs", optional_argument, NULL, 'e'},
{"form-feed", no_argument, NULL, 'f'},
{"header", required_argument, NULL, 'h'},
{"output-tabs", optional_argument, NULL, 'i'},
{"join-lines", no_argument, NULL, 'J'},
{"length", required_argument, NULL, 'l'},
{"merge", no_argument, NULL, 'm'},
{"number-lines", optional_argument, NULL, 'n'},
{"first-line-number", required_argument, NULL, 'N'},
{"indent", required_argument, NULL, 'o'},
{"no-file-warnings", no_argument, NULL, 'r'},
{"separator", optional_argument, NULL, 's'},
{"sep-string", optional_argument, NULL, 'S'},
{"omit-header", no_argument, NULL, 't'},
{"omit-pagination", no_argument, NULL, 'T'},
{"show-nonprinting", no_argument, NULL, 'v'},
{"width", required_argument, NULL, 'w'},
{"page-width", required_argument, NULL, 'W'},
{GETOPT_HELP_OPTION_DECL},
{GETOPT_VERSION_OPTION_DECL},
{NULL, 0, NULL, 0}
};
static void
integer_overflow (void)
{
die (EXIT_FAILURE, 0, _("integer overflow"));
}
/* Return the number of columns that have either an open file or
stored lines. */
static unsigned int _GL_ATTRIBUTE_PURE
cols_ready_to_print (void)
{
COLUMN *q;
unsigned int i;
unsigned int n;
n = 0;
for (q = column_vector, i = 0; i < columns; ++q, ++i)
if (q->status == OPEN
|| q->status == FF_FOUND /* With -b: To print a header only */
|| (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0))
++n;
return n;
}
/* Estimate first_ / last_page_number
using option +FIRST_PAGE:LAST_PAGE */
static bool
first_last_page (int oi, char c, char const *pages)
{
char *p;
uintmax_t first;
uintmax_t last = UINTMAX_MAX;
strtol_error err = xstrtoumax (pages, &p, 10, &first, "");
if (err != LONGINT_OK && err != LONGINT_INVALID_SUFFIX_CHAR)
xstrtol_fatal (err, oi, c, long_options, pages);
if (p == pages || !first)
return false;
if (*p == ':')
{
char const *p1 = p + 1;
err = xstrtoumax (p1, &p, 10, &last, "");
if (err != LONGINT_OK)
xstrtol_fatal (err, oi, c, long_options, pages);
if (p1 == p || last < first)
return false;
}
if (*p)
return false;
first_page_number = first;
last_page_number = last;
return true;
}
/* Parse column count string S, and if it's valid (1 or larger and
within range of the type of 'columns') set the global variables
columns and explicit_columns. Otherwise, exit with a diagnostic. */
static void
parse_column_count (char const *s)
{
getoptnum (s, 1, &columns, _("invalid number of columns"));
explicit_columns = true;
}
/* Estimate length of col_sep_string with option -S. */
static void
separator_string (const char *optarg_S)
{
size_t len = strlen (optarg_S);
if (INT_MAX < len)
integer_overflow ();
col_sep_length = len;
col_sep_string = optarg_S;
}
int
main (int argc, char **argv)
{
unsigned int n_files;
bool old_options = false;
bool old_w = false;
bool old_s = false;
char **file_names;
/* Accumulate the digits of old-style options like -99. */
char *column_count_string = NULL;
size_t n_digits = 0;
size_t n_alloc = 0;
initialize_main (&argc, &argv);
set_program_name (argv[0]);
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
atexit (close_stdout);
n_files = 0;
file_names = (argc > 1
? xnmalloc (argc - 1, sizeof (char *))
: NULL);
while (true)
{
int oi = -1;
int c = getopt_long (argc, argv, short_options, long_options, &oi);
if (c == -1)
break;
if (ISDIGIT (c))
{
/* Accumulate column-count digits specified via old-style options. */
if (n_digits + 1 >= n_alloc)
column_count_string
= X2REALLOC (column_count_string, &n_alloc);
column_count_string[n_digits++] = c;
column_count_string[n_digits] = '\0';
continue;
}
n_digits = 0;
switch (c)
{
case 1: /* Non-option argument. */
/* long option --page dominates old '+FIRST_PAGE ...'. */
if (! (first_page_number == 0
&& *optarg == '+' && first_last_page (-2, '+', optarg + 1)))
file_names[n_files++] = optarg;
break;
case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */
{ /* dominates old opt +... */
if (! optarg)
die (EXIT_FAILURE, 0,
_("'--pages=FIRST_PAGE[:LAST_PAGE]' missing argument"));
else if (! first_last_page (oi, 0, optarg))
die (EXIT_FAILURE, 0, _("invalid page range %s"),
quote (optarg));
break;
}
case COLUMNS_OPTION: /* --columns=COLUMN */
{
parse_column_count (optarg);
/* If there was a prior column count specified via the
short-named option syntax, e.g., -9, ensure that this
long-name-specified value overrides it. */
free (column_count_string);
column_count_string = NULL;
n_alloc = 0;
break;
}
case 'a':
print_across_flag = true;
storing_columns = false;
break;
case 'b':
balance_columns = true;
break;
case 'c':
use_cntrl_prefix = true;
break;
case 'd':
double_space = true;
break;
case 'D':
date_format = optarg;
break;
case 'e':
if (optarg)
getoptarg (optarg, 'e', &input_tab_char,
&chars_per_input_tab);
/* Could check tab width > 0. */
untabify_input = true;
break;
case 'f':
case 'F':
use_form_feed = true;
break;
case 'h':
custom_header = optarg;
break;
case 'i':
if (optarg)
getoptarg (optarg, 'i', &output_tab_char,
&chars_per_output_tab);
/* Could check tab width > 0. */
tabify_output = true;
break;
case 'J':
join_lines = true;
break;
case 'l':
getoptnum (optarg, 1, &lines_per_page,
_("'-l PAGE_LENGTH' invalid number of lines"));
break;
case 'm':
parallel_files = true;
storing_columns = false;
break;
case 'n':
numbered_lines = true;
if (optarg)
getoptarg (optarg, 'n', &number_separator,
&chars_per_number);
break;
case 'N':
skip_count = false;
getoptnum (optarg, INT_MIN, &start_line_num,
_("'-N NUMBER' invalid starting line number"));
break;
case 'o':
getoptnum (optarg, 0, &chars_per_margin,
_("'-o MARGIN' invalid line offset"));
break;
case 'r':