1 /* $OpenBSD: fmt.c,v 1.21 2004/04/01 23:14:19 tedu Exp $ */
3 /* Sensible version of fmt
5 * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ]
7 * Since the documentation for the original fmt is so poor, here
8 * is an accurate description of what this one does. It's usually
9 * the same. The *mechanism* used may differ from that suggested
10 * here. Note that we are *not* entirely compatible with fmt,
11 * because fmt gets so many things wrong.
13 * 1. Tabs are expanded, assuming 8-space tab stops.
14 * If the `-t <n>' option is given, we assume <n>-space
16 * Trailing blanks are removed from all lines.
17 * x\b == nothing, for any x other than \b.
18 * Other control characters are simply stripped. This
20 * 2. Each line is split into leading whitespace and
21 * everything else. Maximal consecutive sequences of
22 * lines with the same leading whitespace are considered
23 * to form paragraphs, except that a blank line is always
24 * a paragraph to itself.
25 * If the `-p' option is given then the first line of a
26 * paragraph is permitted to have indentation different
27 * from that of the other lines.
28 * If the `-m' option is given then a line that looks
29 * like a mail message header, if it is not immediately
30 * preceded by a non-blank non-message-header line, is
31 * taken to start a new paragraph, which also contains
32 * any subsequent lines with non-empty leading whitespace.
33 * Unless the `-n' option is given, lines beginning with
34 * a . (dot) are not formatted.
35 * 3. The "everything else" is split into words; a word
36 * includes its trailing whitespace, and a word at the
37 * end of a line is deemed to be followed by a single
38 * space, or two spaces if it ends with a sentence-end
39 * character. (See the `-d' option for how to change that.)
40 * If the `-s' option has been given, then a word's trailing
41 * whitespace is replaced by what it would have had if it
42 * had occurred at end of line.
43 * 4. Each paragraph is sent to standard output as follows.
44 * We output the leading whitespace, and then enough words
45 * to make the line length as near as possible to the goal
46 * without exceeding the maximum. (If a single word would
47 * exceed the maximum, we output that anyway.) Of course
48 * the trailing whitespace of the last word is ignored.
49 * We then emit a newline and start again if there are any
51 * Note that for a blank line this translates as "We emit
53 * If the `-l <n>' option is given, then leading whitespace
54 * is modified slightly: <n> spaces are replaced by a tab.
55 * Indented paragraphs (see above under `-p') make matters
56 * more complicated than this suggests. Actually every paragraph
57 * has two `leading whitespace' values; the value for the first
58 * line, and the value for the most recent line. (While processing
59 * the first line, the two are equal. When `-p' has not been
60 * given, they are always equal.) The leading whitespace
61 * actually output is that of the first line (for the first
62 * line of *output*) or that of the most recent line (for
63 * all other lines of output).
64 * When `-m' has been given, message header paragraphs are
65 * taken as having first-leading-whitespace empty and
66 * subsequent-leading-whitespace two spaces.
68 * Multiple input files are formatted one at a time, so that a file
69 * never ends in the middle of a line.
71 * There's an alternative mode of operation, invoked by giving
72 * the `-c' option. In that case we just center every line,
73 * and most of the other options are ignored. This should
74 * really be in a separate program, but we must stay compatible
77 * QUERY: Should `-m' also try to do the right thing with quoted text?
78 * QUERY: `-b' to treat backslashed whitespace as old `fmt' does?
79 * QUERY: Option meaning `never join lines'?
80 * QUERY: Option meaning `split in mid-word to avoid overlong lines'?
81 * (Those last two might not be useful, since we have `fold'.)
83 * Differences from old `fmt':
85 * - We have many more options. Options that aren't understood
86 * generate a lengthy usage message, rather than being
87 * treated as filenames.
88 * - Even with `-m', our handling of message headers is
89 * significantly different. (And much better.)
90 * - We don't treat `\ ' as non-word-breaking.
91 * - Downward changes of indentation start new paragraphs
92 * for us, as well as upward. (I think old `fmt' behaves
93 * in the way it does in order to allow indented paragraphs,
94 * but this is a broken way of making indented paragraphs
96 * - Given the choice of going over or under |goal_length|
97 * by the same amount, we go over; old `fmt' goes under.
98 * - We treat `?' as ending a sentence, and not `:'. Old `fmt'
100 * - We return approved return codes. Old `fmt' returns
101 * 1 for some errors, and *the number of unopenable files*
102 * when that was all that went wrong.
103 * - We have fewer crashes and more helpful error messages.
104 * - We don't turn spaces into tabs at starts of lines unless
105 * specifically requested.
106 * - New `fmt' is somewhat smaller and slightly faster than
111 * None known. There probably are some, though.
115 * I believe this code to be pretty portable. It does require
116 * that you have `getopt'. If you need to include "getopt.h"
117 * for this (e.g., if your system didn't come with `getopt'
118 * and you installed it yourself) then you should arrange for
119 * NEED_getopt_h to be #defined.
121 * Everything here should work OK even on nasty 16-bit
122 * machines and nice 64-bit ones. However, it's only really
123 * been tested on my FreeBSD machine. Your mileage may vary.
126 /* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
128 * Redistribution and use of this code, in source or binary forms,
129 * with or without modification, are permitted subject to the following
132 * - Redistribution of source code must retain the above copyright
133 * notice, this list of conditions and the following disclaimer.
135 * - If you distribute modified source code it must also include
136 * a notice saying that it has been modified, and giving a brief
137 * description of what changes have been made.
139 * Disclaimer: I am not responsible for the results of using this code.
140 * If it formats your hard disc, sends obscene messages to
141 * your boss and kills your children then that's your problem
142 * not mine. I give absolutely no warranty of any sort as to
143 * what the program will do, and absolutely refuse to be held
144 * liable for any consequences of your using it.
145 * Thank you. Have a nice day.
149 * Revision 1.5 1998/03/02 18:02:21 gjm11
150 * Minor changes for portability.
152 * Revision 1.4 1997/10/01 11:51:28 gjm11
153 * Repair broken indented-paragraph handling.
154 * Add mail message header stuff.
155 * Improve comments and layout.
156 * Make usable with non-BSD systems.
157 * Add revision display to usage message.
159 * Revision 1.3 1997/09/30 16:24:47 gjm11
160 * Add copyright notice, rcsid string and log message.
162 * Revision 1.2 1997/09/30 16:13:39 gjm11
163 * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h .
164 * Parse options with `getopt'. Clean up code generally.
165 * Make comments more accurate.
167 * Revision 1.1 1997/09/30 11:29:57 gjm11
171 #define _XOPEN_SOURCE 700
174 static const char copyright
[] =
175 "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n";
176 #endif /* not lint */
188 /* Something that, we hope, will never be a genuine line length,
191 #define SILLY ((size_t)-1)
193 #define XMALLOC(x) xrealloc(0,x)
195 /* Global variables */
197 static char *progname
;
198 static int centerP
= 0; /* Try to center lines? */
199 static size_t goal_length
= 0; /* Target length for output lines */
200 static size_t max_length
= 0; /* Maximum length for output lines */
201 static int coalesce_spaces_P
= 0; /* Coalesce multiple whitespace -> ' ' ? */
202 static int allow_indented_paragraphs
= 0; /* Can first line have diff. ind.? */
203 static int tab_width
= 8; /* Number of spaces per tab stop */
204 static size_t output_tab_width
= 8; /* Ditto, when squashing leading spaces */
205 static const wchar_t *sentence_enders
= L
".?!"; /* Double-space after these */
206 static int grok_mail_headers
= 0; /* treat embedded mail headers magically? */
207 static int format_troff
= 0; /* Format troff? */
209 static int n_errors
= 0; /* Number of failed files. Return on exit. */
210 static wchar_t *output_buffer
= NULL
; /* Output line will be built here */
211 static size_t x
; /* Horizontal position in output line */
212 static size_t x0
; /* Ditto, ignoring leading whitespace */
213 static size_t output_buffer_length
= 0;
214 static size_t pending_spaces
; /* Spaces to add before next word */
215 static int output_in_paragraph
= 0; /* Any of current para written out yet? */
219 static void process_named_file(const char *);
220 static void process_stream(FILE *, const char *);
221 static size_t indent_length(const wchar_t *, size_t);
222 static int might_be_header(const wchar_t *);
223 static void new_paragraph(size_t, size_t);
224 static void output_word(size_t, size_t, const wchar_t *, size_t, size_t);
225 static void output_indent(size_t);
226 static void center_stream(FILE *, const char *);
227 static wchar_t *get_line(FILE *, size_t *);
228 static void *xrealloc(void *, size_t);
231 fmt_errx(int eval
, const char *fmt
, ...)
236 fprintf(stderr
, "%s: ", progname
);
237 vfprintf(stderr
, fmt
, args
);
245 fmt_warn(const char *fmt
, ...)
250 fprintf(stderr
, "%s: ", progname
);
251 vfprintf(stderr
, fmt
, args
);
252 fprintf(stderr
, ": %s\n", strerror(errno
));
256 /* I used to use |strtoul| for this, but (1) not all systems have it
257 * and (2) it's probably better to use |strtol| to detect negative
259 * If |fussyp==0| then we don't complain about non-numbers
260 * (returning 0 instead), but we do complain about bad numbers.
263 get_positive(const char *s
, const char *err_mess
, int fussyP
)
266 long result
= strtol(s
, &t
, 0);
275 Lose
: fmt_errx(2, "%s", err_mess
);
277 return (size_t)result
;
281 get_nonnegative(const char *s
, const char *err_mess
, int fussyP
)
284 long result
= strtol(s
, &t
, 0);
293 Lose
: fmt_errx(2, "%s", err_mess
);
295 return (size_t)result
;
298 /* Here is perhaps the right place to mention that this code is
299 * all in top-down order. Hence, |main| comes first.
302 main(int argc
, char *argv
[])
304 int ch
; /* used for |getopt| processing */
309 (void)setlocale(LC_CTYPE
, "");
311 /* 1. Grok parameters. */
313 while ((ch
= getopt(argc
, argv
, "0123456789cd:hl:mnpst:w:")) != -1)
321 len
= mbsrtowcs(NULL
, &src
, 0, NULL
);
322 if (len
== (size_t)-1)
323 fmt_errx(2, "bad sentence-ending character set: %s", strerror(errno
));
324 tmp
= XMALLOC((len
+ 1) * sizeof(wchar_t));
325 mbsrtowcs(tmp
, &src
, len
+ 1, NULL
);
326 sentence_enders
= tmp
;
330 = get_nonnegative(optarg
, "output tab width must be non-negative", 1);
333 grok_mail_headers
= 1;
339 allow_indented_paragraphs
= 1;
342 coalesce_spaces_P
= 1;
345 tab_width
= get_positive(optarg
, "tab width must be positive", 1);
348 goal_length
= get_positive(optarg
, "width must be positive", 1);
349 max_length
= goal_length
;
351 case '0': case '1': case '2': case '3': case '4': case '5':
352 case '6': case '7': case '8': case '9':
354 * XXX this is not a stylistically approved use of
357 if (goal_length
== 0) {
360 p
= argv
[optind
- 1];
361 if (p
[0] == '-' && p
[1] == ch
&& !p
[2])
362 goal_length
= get_positive(++p
, "width must be nonzero", 1);
364 goal_length
= get_positive(argv
[optind
] + 1,
365 "width must be nonzero", 1);
366 max_length
= goal_length
;
372 "usage: fmt [-cmps] [-d chars] [-l num] [-t num]\n"
373 " [-w width | -width | goal [maximum]] [file ...]\n"
374 "Options: -c center each line instead of formatting\n"
375 " -d <chars> double-space after <chars> at line end\n"
376 " -l <n> turn each <n> spaces at start of line into a tab\n"
377 " -m try to make sure mail header lines stay separate\n"
378 " -n format lines beginning with a dot\n"
379 " -p allow indented paragraphs\n"
380 " -s coalesce whitespace inside lines\n"
381 " -t <n> have tabs every <n> columns\n"
382 " -w <n> set maximum width to <n>\n"
383 " goal set target width to goal\n");
384 exit(ch
== 'h' ? 0 : 2);
389 /* [ goal [ maximum ] ] */
391 if (argc
> 0 && goal_length
== 0
392 && (goal_length
= get_positive(*argv
, "goal length must be positive", 0))
397 && (max_length
= get_positive(*argv
, "max length must be positive", 0))
401 if (max_length
< goal_length
)
402 fmt_errx(2, "max length must be >= goal length");
405 if (goal_length
== 0)
408 max_length
= goal_length
+ 10;
409 if (max_length
>= SILLY
/ sizeof(wchar_t))
410 fmt_errx(2, "max length too large");
411 /* really needn't be longer */
412 output_buffer
= XMALLOC((max_length
+ 1) * sizeof(wchar_t));
414 /* 2. Process files. */
418 process_named_file(*argv
++);
420 process_stream(stdin
, "standard input");
425 return n_errors
? 2 : 0;
429 /* Process a single file, given its name.
432 process_named_file(const char *name
)
434 FILE *f
= fopen(name
, "r");
437 fmt_warn("%s", name
);
440 process_stream(f
, name
);
442 fmt_warn("%s", name
);
449 /* Types of mail header continuation lines:
452 hdr_ParagraphStart
= -1,
458 /* Process a stream. This is where the real work happens,
459 * except that centering is handled separately.
462 process_stream(FILE *stream
, const char *name
)
464 size_t last_indent
= SILLY
; /* how many spaces in last indent? */
465 size_t para_line_number
= 0; /* how many lines already read in this para? */
466 size_t first_indent
= SILLY
; /* indentation of line 0 of paragraph */
467 HdrType prev_header_type
= hdr_ParagraphStart
;
469 /* ^-- header_type of previous line; -1 at para start */
474 center_stream(stream
, name
);
477 while ((line
= get_line(stream
, &length
)) != NULL
) {
478 size_t np
= indent_length(line
, length
);
481 HdrType header_type
= hdr_NonHeader
;
483 if (grok_mail_headers
&& prev_header_type
!= hdr_NonHeader
) {
484 if (np
== 0 && might_be_header(line
))
485 header_type
= hdr_Header
;
486 else if (np
> 0 && prev_header_type
> hdr_NonHeader
)
487 header_type
= hdr_Continuation
;
490 * We need a new paragraph if and only if: this line
491 * is blank, OR it's a troff request (and we don't
492 * format troff), OR it's a mail header, OR it's not
493 * a mail header AND the last line was one, OR the
494 * indentation has changed AND the line isn't a mail
495 * header continuation line AND this isn't the
496 * second line of an indented paragraph.
499 || (line
[0] == '.' && !format_troff
)
500 || header_type
== hdr_Header
501 || (header_type
== hdr_NonHeader
&& prev_header_type
> hdr_NonHeader
)
502 || (np
!= last_indent
503 && header_type
!= hdr_Continuation
504 && (!allow_indented_paragraphs
|| para_line_number
!= 1))) {
505 new_paragraph(output_in_paragraph
? last_indent
: first_indent
, np
);
506 para_line_number
= 0;
509 if (header_type
== hdr_Header
)
510 last_indent
= 2; /* for cont. lines */
511 if (length
== 0 || (line
[0] == '.' && !format_troff
)) {
515 wprintf(L
"%.*ls\n", (int)length
,
517 prev_header_type
= hdr_ParagraphStart
;
522 * If this is an indented paragraph other
523 * than a mail header continuation, set
526 if (np
!= last_indent
&&
527 header_type
!= hdr_Continuation
)
530 prev_header_type
= header_type
;
537 /* Find word end and count spaces after it */
538 size_t word_length
= 0, space_length
= 0;
540 while (n
+ word_length
< length
&&
541 line
[n
+ word_length
] != ' ')
543 space_length
= word_length
;
544 while (n
+ space_length
< length
&&
545 line
[n
+ space_length
] == ' ')
547 /* Send the word to the output machinery. */
548 output_word(first_indent
, last_indent
,
549 line
+ n
, word_length
,
550 space_length
- word_length
);
556 new_paragraph(output_in_paragraph
? last_indent
: first_indent
, 0);
557 if (ferror(stream
)) {
558 fmt_warn("%s", name
);
563 /* How long is the indent on this line?
566 indent_length(const wchar_t *line
, size_t length
)
570 while (n
< length
&& *line
++ == ' ')
575 /* Might this line be a mail header?
576 * We deem a line to be a possible header if it matches the
577 * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
578 * as in RFC whatever-number-it-is; we want to be gratuitously
579 * conservative to avoid mangling ordinary civilised text.
582 might_be_header(const wchar_t *line
)
584 if (!iswupper(*line
++))
586 while (*line
&& (iswalnum(*line
) || *line
== '-'))
588 return (*line
== ':' && iswspace(line
[1]));
591 /* Begin a new paragraph with an indent of |indent| spaces.
594 new_paragraph(size_t old_indent
, size_t indent
)
596 if (output_buffer_length
) {
598 output_indent(old_indent
);
599 wprintf(L
"%.*ls\n", (int)output_buffer_length
, output_buffer
);
603 output_buffer_length
= 0;
605 output_in_paragraph
= 0;
608 /* Output spaces or tabs for leading indentation.
611 output_indent(size_t n_spaces
)
613 if (output_tab_width
) {
614 while (n_spaces
>= output_tab_width
) {
616 n_spaces
-= output_tab_width
;
619 while (n_spaces
-- > 0)
623 /* Output a single word, or add it to the buffer.
624 * indent0 and indent1 are the indents to use on the first and subsequent
625 * lines of a paragraph. They'll often be the same, of course.
628 output_word(size_t indent0
, size_t indent1
, const wchar_t *word
, size_t length
, size_t spaces
)
631 size_t indent
= output_in_paragraph
? indent1
: indent0
;
636 for (p
= word
, width
= 0; p
< &word
[length
]; p
++)
637 width
+= (cwidth
= wcwidth(*p
)) > 0 ? cwidth
: 1;
639 new_x
= x
+ pending_spaces
+ width
;
642 * If either |spaces==0| (at end of line) or |coalesce_spaces_P|
643 * (squashing internal whitespace), then add just one space; except
644 * that if the last character was a sentence-ender we actually add
647 if (coalesce_spaces_P
|| spaces
== 0)
648 spaces
= wcschr(sentence_enders
, word
[length
- 1]) ? 2 : 1;
650 if (new_x
<= goal_length
) {
652 * After adding the word we still aren't at the goal length,
653 * so clearly we add it to the buffer rather than outputting
656 wmemset(output_buffer
+ output_buffer_length
, L
' ',
658 x0
+= pending_spaces
;
660 output_buffer_length
+= pending_spaces
;
661 wmemcpy(output_buffer
+ output_buffer_length
, word
, length
);
664 output_buffer_length
+= length
;
665 pending_spaces
= spaces
;
668 * Adding the word takes us past the goal. Print the
669 * line-so-far, and the word too iff either (1) the lsf is
670 * empty or (2) that makes us nearer the goal but doesn't
671 * take us over the limit, or (3) the word on its own takes
672 * us over the limit. In case (3) we put a newline in
676 output_indent(indent
);
677 wprintf(L
"%.*ls", (int)output_buffer_length
, output_buffer
);
678 if (x0
== 0 || (new_x
<= max_length
&&
679 new_x
- goal_length
<= goal_length
- x
)) {
680 wprintf(L
"%*ls", (int)pending_spaces
, L
"");
684 * If the word takes us over the limit on its own,
685 * just spit it out and don't bother buffering it.
687 if (indent
+ width
> max_length
) {
690 output_indent(indent
);
692 wprintf(L
"%.*ls", (int)length
, word
);
696 output_buffer_length
= 0;
698 wmemcpy(output_buffer
, word
, length
);
701 pending_spaces
= spaces
;
702 output_buffer_length
= length
;
706 output_in_paragraph
= 1;
710 /* Process a stream, but just center its lines rather than trying to
711 * format them neatly.
714 center_stream(FILE *stream
, const char *name
)
721 while ((line
= get_line(stream
, &length
)) != NULL
) {
724 while (l
> 0 && iswspace(*line
)) {
729 for (p
= line
, width
= 0; p
< &line
[length
]; p
++)
730 width
+= (cwidth
= wcwidth(*p
)) > 0 ? cwidth
: 1;
732 while (l
< goal_length
) {
736 wprintf(L
"%.*ls\n", (int)length
, line
);
738 if (ferror(stream
)) {
739 fmt_warn("%s", name
);
744 /* Get a single line from a stream. Expand tabs, strip control
745 * characters and trailing whitespace, and handle backspaces.
746 * Return the address of the buffer containing the line, and
747 * put the length of the line in |lengthp|.
748 * This can cope with arbitrarily long lines, and with lines
749 * without terminating \n.
750 * If there are no characters left or an error happens, we
752 * Don't confuse |spaces_pending| here with the global
756 get_line(FILE *stream
, size_t *lengthp
)
758 static wchar_t *buf
= NULL
;
759 static size_t length
= 0;
762 size_t spaces_pending
= 0;
769 buf
= XMALLOC(length
* sizeof(wchar_t));
771 while ((ch
= getwc(stream
)) != '\n' && ch
!= WEOF
) {
772 if (len
+ spaces_pending
== 0 && ch
== '.' && !format_troff
)
776 else if (troff
|| iswprint(ch
)) {
777 while (len
+ spaces_pending
>= length
) {
779 buf
= xrealloc(buf
, length
* sizeof(wchar_t));
781 while (spaces_pending
> 0) {
787 col
+= (cwidth
= wcwidth(ch
)) > 0 ? cwidth
: 1;
788 } else if (ch
== '\t')
789 spaces_pending
+= tab_width
-
790 (col
+ spaces_pending
) % tab_width
;
791 else if (ch
== '\b') {
799 return (len
> 0 || ch
!= WEOF
) ? buf
: 0;
802 /* (Re)allocate some memory, exiting with an error if we can't.
805 xrealloc(void *ptr
, size_t nbytes
)
807 void *p
= realloc(ptr
, nbytes
);
810 fmt_errx(1, "out of memory");