1 /*	$OpenBSD: fmt.c,v 1.23 2005/03/08 23:34:43 cloder Exp $	*/
2 
3 /* Sensible version of fmt
4  *
5  * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ]
6  *
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.
12  *
13  * 1. Tabs are expanded, assuming 8-space tab stops.
14  *    If the `-t <n>' option is given, we assume <n>-space
15  *    tab stops instead.
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
19  *    includes \r.
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
50  *    words left.
51  *    Note that for a blank line this translates as "We emit
52  *    a newline".
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.
67  *
68  * Multiple input files are formatted one at a time, so that a file
69  * never ends in the middle of a line.
70  *
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
75  * with old `fmt'.
76  *
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'.)
82  *
83  * Differences from old `fmt':
84  *
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
95  *     behave right.)
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'
99  *     does the reverse.
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
107  *     old `fmt'.
108  *
109  * Bugs:
110  *
111  *   None known. There probably are some, though.
112  *
113  * Portability:
114  *
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.
120  *
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.
124  */
125 
126 /* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
127  *
128  * Redistribution and use of this code, in source or binary forms,
129  * with or without modification, are permitted subject to the following
130  * conditions:
131  *
132  *  - Redistribution of source code must retain the above copyright
133  *    notice, this list of conditions and the following disclaimer.
134  *
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.
138  *
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.
146  */
147 
148 /* RCS change log:
149  * Revision 1.5  1998/03/02 18:02:21  gjm11
150  * Minor changes for portability.
151  *
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.
158  *
159  * Revision 1.3  1997/09/30 16:24:47  gjm11
160  * Add copyright notice, rcsid string and log message.
161  *
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.
166  *
167  * Revision 1.1  1997/09/30 11:29:57  gjm11
168  * Initial revision
169  */
170 
171 #include <sys/cdefs.h>
172 __COPYRIGHT("Copyright (c) 1997 Gareth McCaughan. All rights reserved.");
173 
174 #include <ctype.h>
175 #include <err.h>
176 #include <locale.h>
177 #include <stdio.h>
178 #include <stdlib.h>
179 #include <string.h>
180 #include <sysexits.h>
181 #include <unistd.h>
182 
183 /* Something that, we hope, will never be a genuine line length,
184  * indentation etc.
185  */
186 #define SILLY ((size_t)-1)
187 
188 /* I used to use |strtoul| for this, but (1) not all systems have it
189  * and (2) it's probably better to use |strtol| to detect negative
190  * numbers better.
191  * If |fussyp==0| then we don't complain about non-numbers
192  * (returning 0 instead), but we do complain about bad numbers.
193  */
194 static size_t
get_positive(const char * s,const char * err_mess,int fussyP)195 get_positive(const char *s, const char *err_mess, int fussyP)
196 {
197 	char *t;
198 	long result = strtol(s, &t, 0);
199 
200 	if (*t) {
201 		if (fussyP)
202 			goto Lose;
203 		else
204 			return 0;
205 	}
206 	if (result <= 0) {
207 Lose:
208 		errx(EX_USAGE, "%s", err_mess);
209 	}
210 
211 	return (size_t) result;
212 }
213 
214 /* Global variables */
215 
216 static int centerP = 0;				/* Try to center lines? */
217 static size_t goal_length = 0;			/* Target length for output lines */
218 static size_t max_length = 0;			/* Maximum length for output lines */
219 static int coalesce_spaces_P = 0;		/* Coalesce multiple whitespace -> ' ' ? */
220 static int allow_indented_paragraphs = 0;	/* Can first line have diff. ind.? */
221 static int tab_width = 8;			/* Number of spaces per tab stop */
222 static size_t output_tab_width = 0;		/* Ditto, when squashing leading spaces */
223 static const char *sentence_enders = ".?!";	/* Double-space after these */
224 static int grok_mail_headers = 0;		/* treat embedded mail headers magically? */
225 static int format_troff = 0;			/* Format troff? */
226 
227 static int n_errors = 0;			/* Number of failed files. Return on exit. */
228 static char *output_buffer = NULL;		/* Output line will be built here */
229 static size_t x;				/* Horizontal position in output line */
230 static size_t x0;				/* Ditto, ignoring leading whitespace */
231 static size_t pending_spaces;			/* Spaces to add before next word */
232 static int output_in_paragraph = 0;		/* Any of current para written out yet? */
233 
234 /* Prototypes */
235 
236 static void	process_named_file(const char *);
237 static void	process_stream(FILE *, const char *);
238 static size_t	indent_length(const char *, size_t);
239 static int	might_be_header(const unsigned char *);
240 static void	new_paragraph(size_t, size_t);
241 static void	output_word(size_t, size_t, const char *, size_t, size_t);
242 static void	output_indent(size_t);
243 static void	center_stream(FILE *, const char *);
244 static char	*get_line(FILE *, size_t *);
245 static void	*xrealloc(void *, size_t);
246 void		usage(void);
247 
248 #define XMALLOC(x) xrealloc(0, x)
249 
250 /* Here is perhaps the right place to mention that this code is
251  * all in top-down order. Hence, |main| comes first.
252  */
253 int
main(int argc,char * argv[])254 main(int argc, char *argv[])
255 {
256 	int ch;			/* used for |getopt| processing */
257 
258 #ifndef __MirBSD__
259 	(void)setlocale(LC_CTYPE, "");
260 #endif
261 
262 	/* 1. Grok parameters. */
263 	while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) {
264 		switch (ch) {
265 		case 'c':
266 			centerP = 1;
267 			break;
268 		case 'd':
269 			sentence_enders = optarg;
270 			break;
271 		case 'l':
272 			output_tab_width
273 				= get_positive(optarg, "output tab width must be positive", 1);
274 			break;
275 		case 'm':
276 			grok_mail_headers = 1;
277 			break;
278 		case 'n':
279 			format_troff = 1;
280 			break;
281 		case 'p':
282 			allow_indented_paragraphs = 1;
283 			break;
284 		case 's':
285 			coalesce_spaces_P = 1;
286 			break;
287 		case 't':
288 			tab_width = get_positive(optarg, "tab width must be positive", 1);
289 			break;
290 		case 'w':
291 			goal_length = get_positive(optarg, "width must be positive", 1);
292 			max_length = goal_length;
293 			break;
294 		case '0': case '1': case '2': case '3': case '4': case '5':
295 		case '6': case '7': case '8': case '9':
296 			/* XXX  this is not a stylistically approved use of getopt() */
297 			if (goal_length == 0) {
298 				char *p;
299 
300 				p = argv[optind - 1];
301 				if (p[0] == '-' && p[1] == ch && !p[2])
302 					goal_length = get_positive(++p, "width must be nonzero", 1);
303 				else
304 					goal_length = get_positive(argv[optind]+1,
305 							"width must be nonzero", 1);
306 				max_length = goal_length;
307 			}
308 			break;
309 		case 'h':
310 		default:
311 			usage();
312 			/* NOT REACHED */
313 		}
314 	}
315 
316 	argc -= optind;
317 	argv += optind;
318 
319 	/* [ goal [ maximum ] ] */
320 	if (argc > 0 && goal_length == 0 &&
321 	    (goal_length = get_positive(*argv,"goal length must be positive", 0)) != 0) {
322 		--argc;
323 		++argv;
324 		if (argc > 0 && (max_length = get_positive(*argv,"max length must be positive", 0)) != 0) {
325 			--argc;
326 			++argv;
327 			if (max_length < goal_length)
328 				errx(EX_USAGE, "max length must be >= goal length");
329 		}
330 	}
331 
332 	if (goal_length == 0)
333 		goal_length = 65;
334 	if (max_length == 0)
335 		max_length = goal_length+10;
336 	output_buffer = XMALLOC(max_length+1);	/* really needn't be longer */
337 
338 	/* 2. Process files. */
339 
340 	if (argc > 0) {
341 		while (argc-- > 0)
342 			process_named_file(*argv++);
343 	} else {
344 		process_stream(stdin, "standard input");
345 	}
346 
347 	/* We're done. */
348 	return n_errors ? EX_NOINPUT : 0;
349 
350 }
351 
352 /* Process a single file, given its name.
353  */
354 static void
process_named_file(const char * name)355 process_named_file(const char *name)
356 {
357 	FILE *f;
358 
359 	if ((f = fopen(name, "r")) == NULL) {
360 		warn("%s", name);
361 		++n_errors;
362 	} else {
363 		process_stream(f, name);
364 		fclose(f);
365 	}
366 }
367 
368 /* Types of mail header continuation lines:
369  */
370 typedef enum {
371 	hdr_ParagraphStart	= -1,
372 	hdr_NonHeader		= 0,
373 	hdr_Header		= 1,
374 	hdr_Continuation	= 2
375 } HdrType;
376 
377 /* Process a stream. This is where the real work happens,
378  * except that centering is handled separately.
379  */
380 static void
process_stream(FILE * stream,const char * name)381 process_stream(FILE *stream, const char *name)
382 {
383 	size_t n;
384 	size_t np;
385 	size_t last_indent = SILLY;	/* how many spaces in last indent? */
386 	size_t para_line_number = 0;	/* how many lines already read in this para? */
387 	size_t first_indent = SILLY;	/* indentation of line 0 of paragraph */
388 	HdrType prev_header_type = hdr_ParagraphStart;
389 	HdrType header_type;
390 
391 	/* ^-- header_type of previous line; -1 at para start */
392 	char *line;
393 	size_t length;
394 
395 	if (centerP) {
396 		center_stream(stream, name);
397 		return;
398 	}
399 
400 	while ((line = get_line(stream, &length)) != NULL) {
401 		np = indent_length(line, length);
402 		header_type = hdr_NonHeader;
403 		if (grok_mail_headers && prev_header_type != hdr_NonHeader) {
404 			if (np == 0 && might_be_header(line))
405 				header_type = hdr_Header;
406 			else if (np > 0 && prev_header_type>hdr_NonHeader)
407 				header_type = hdr_Continuation;
408 		}
409 
410 		/* We need a new paragraph if and only if:
411 		 *   this line is blank,
412 		 *   OR it's a troff request,
413 		 *   OR it's a mail header,
414 		 *   OR it's not a mail header AND the last line was one,
415 		 *   OR the indentation has changed
416 		 *      AND the line isn't a mail header continuation line
417 		 *      AND this isn't the second line of an indented paragraph.
418 		 */
419 		if (length == 0 || (line[0] == '.' && !format_troff) ||
420 		    header_type == hdr_Header ||
421 		    (header_type == hdr_NonHeader && prev_header_type > hdr_NonHeader) ||
422 		    (np != last_indent && header_type != hdr_Continuation &&
423 		    (!allow_indented_paragraphs || para_line_number != 1)) ) {
424 			new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
425 			para_line_number = 0;
426 			first_indent = np;
427 			last_indent = np;
428 
429 			/* nroff compatibility */
430 			if (length > 0 && line[0] == '.' && !format_troff) {
431 				printf("%.*s\n", (int)length, line);
432 				continue;
433 			}
434 			if (header_type == hdr_Header)
435 				last_indent = 2;	/* for cont. lines */
436 			if (length == 0) {
437 				putchar('\n');
438 				prev_header_type = hdr_ParagraphStart;
439 				continue;
440 			} else {
441 				/* If this is an indented paragraph other than a mail header
442 				 * continuation, set |last_indent|.
443 				 */
444 				if (np != last_indent && header_type != hdr_Continuation)
445 					last_indent = np;
446 			}
447 			prev_header_type = header_type;
448 		}
449 
450 		n = np;
451 		while (n < length) {
452 			/* Find word end and count spaces after it */
453 			size_t word_length = 0, space_length = 0;
454 			while (n+word_length < length && line[n+word_length] != ' ')
455 				++word_length;
456 			space_length = word_length;
457 			while (n+space_length < length && line[n+space_length] == ' ')
458 				++space_length;
459 			/* Send the word to the output machinery. */
460 			output_word(first_indent, last_indent,
461 				line+n, word_length, space_length-word_length);
462 			n += space_length;
463 		}
464 		++para_line_number;
465 	}
466 
467 	new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
468 	if (ferror(stream)) {
469 		warn("%s", name);
470 		++n_errors;
471 	}
472 }
473 
474 /* How long is the indent on this line?
475  */
476 static size_t
indent_length(const char * line,size_t length)477 indent_length(const char *line, size_t length)
478 {
479 	size_t n = 0;
480 
481 	while (n < length && *line++ == ' ')
482 		++n;
483 	return n;
484 }
485 
486 /* Might this line be a mail header?
487  * We deem a line to be a possible header if it matches the
488  * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
489  * as in RFC whatever-number-it-is; we want to be gratuitously
490  * conservative to avoid mangling ordinary civilised text.
491  */
492 static int
might_be_header(const unsigned char * line)493 might_be_header(const unsigned char *line)
494 {
495 
496 	if (!isupper(*line++))
497 		return 0;
498 	while (*line && (isalnum(*line) || *line == '-'))
499 		++line;
500 	return (*line == ':' && isspace(line[1]));
501 }
502 
503 /* Begin a new paragraph with an indent of |indent| spaces.
504  */
505 static void
new_paragraph(size_t old_indent,size_t indent)506 new_paragraph(size_t old_indent, size_t indent)
507 {
508 
509 	if (x0) {
510 		if (old_indent > 0)
511 			output_indent(old_indent);
512 		fwrite(output_buffer, 1, x0, stdout);
513 		putchar('\n');
514 	}
515 	x = indent;
516 	x0 = 0;
517 	pending_spaces = 0;
518 	output_in_paragraph = 0;
519 }
520 
521 /* Output spaces or tabs for leading indentation.
522  */
523 static void
output_indent(size_t n_spaces)524 output_indent(size_t n_spaces)
525 {
526 
527 	if (output_tab_width) {
528 		while (n_spaces >= output_tab_width) {
529 			putchar('\t');
530 			n_spaces -= output_tab_width;
531 		}
532 	}
533 	while (n_spaces-- > 0)
534 		putchar(' ');
535 }
536 
537 /* Output a single word, or add it to the buffer.
538  * indent0 and indent1 are the indents to use on the first and subsequent
539  * lines of a paragraph. They'll often be the same, of course.
540  */
541 static void
output_word(size_t indent0,size_t indent1,const char * word,size_t length,size_t spaces)542 output_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces)
543 {
544 	size_t new_x = x + pending_spaces + length;
545 	size_t indent = output_in_paragraph ? indent1 : indent0;
546 
547 	/* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
548 	 * (squashing internal whitespace), then add just one space;
549 	 * except that if the last character was a sentence-ender we
550 	 * actually add two spaces.
551 	 */
552 	if (coalesce_spaces_P || spaces == 0)
553 		spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1;
554 
555 	if (new_x <= goal_length) {
556 		/* After adding the word we still aren't at the goal length,
557 		 * so clearly we add it to the buffer rather than outputing it.
558 		 */
559 		memset(output_buffer+x0, ' ', pending_spaces);
560 		x0 += pending_spaces;
561 		x += pending_spaces;
562 		memcpy(output_buffer+x0, word, length);
563 		x0 += length;
564 		x += length;
565 		pending_spaces = spaces;
566 	} else {
567 		/* Adding the word takes us past the goal. Print the line-so-far,
568 		 * and the word too iff either (1) the lsf is empty or (2) that
569 		 * makes us nearer the goal but doesn't take us over the limit,
570 		 * or (3) the word on its own takes us over the limit.
571 		 * In case (3) we put a newline in between.
572 		 */
573 		if (indent > 0)
574 			output_indent(indent);
575 		fwrite(output_buffer, 1, x0, stdout);
576 		if (x0 == 0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) {
577 			printf("%*s", (int)pending_spaces, "");
578 			goto write_out_word;
579 		} else {
580 			/* If the word takes us over the limit on its own, just
581 			 * spit it out and don't bother buffering it.
582 			 */
583 			if (indent+length > max_length) {
584 				putchar('\n');
585 				if (indent > 0)
586 					output_indent(indent);
587 write_out_word:
588 				fwrite(word, 1, length, stdout);
589 				x0 = 0;
590 				x = indent1;
591 				pending_spaces = 0;
592 			} else {
593 				memcpy(output_buffer, word, length);
594 				x0 = length;
595 				x = length+indent1;
596 				pending_spaces = spaces;
597 			}
598 		}
599 
600 		putchar('\n');
601 		output_in_paragraph = 1;
602 	}
603 }
604 
605 /* Process a stream, but just center its lines rather than trying to
606  * format them neatly.
607  */
608 static void
center_stream(FILE * stream,const char * name)609 center_stream(FILE *stream, const char *name)
610 {
611 	char *line;
612 	size_t length;
613 	size_t l;
614 
615 	while ((line = get_line(stream, &length)) != 0) {
616 		l = length;
617 		while (l > 0 && isspace(*line)) {
618 			++line;
619 			--l;
620 		}
621 
622 		length = l;
623 
624 		while (l < goal_length) {
625 			putchar(' ');
626 			l += 2;
627 		}
628 
629 		fwrite(line, 1, length, stdout);
630 		putchar('\n');
631 	}
632 
633 	if (ferror(stream)) {
634 		warn("%s", name);
635 		++n_errors;
636 	}
637 }
638 
639 /* Get a single line from a stream. Expand tabs, strip control
640  * characters and trailing whitespace, and handle backspaces.
641  * Return the address of the buffer containing the line, and
642  * put the length of the line in |lengthp|.
643  * This can cope with arbitrarily long lines, and with lines
644  * without terminating \n.
645  * If there are no characters left or an error happens, we
646  * return 0.
647  * Don't confuse |spaces_pending| here with the global
648  * |pending_spaces|.
649  */
650 static char *
get_line(FILE * stream,size_t * lengthp)651 get_line(FILE *stream, size_t *lengthp)
652 {
653 	int ch;
654 	int troff = 0;
655 	static char *buf = NULL;
656 	static size_t length = 0;
657 	size_t len = 0;
658 	size_t spaces_pending = 0;
659 
660 	if (buf == NULL) {
661 		length = 100;
662 		buf = XMALLOC(length);
663 	}
664 
665 	while ((ch = getc(stream)) != '\n' && ch != EOF) {
666 		if ((len + spaces_pending == 0) && (ch == '.' && !format_troff))
667 			troff = 1;
668 		if (ch == ' ') {
669 			++spaces_pending;
670 		} else if (troff || !iscntrl(ch)) {
671 			while (len + spaces_pending >= length) {
672 				length *= 2;
673 				buf = xrealloc(buf, length);
674 			}
675 
676 			while (spaces_pending > 0) {
677 				--spaces_pending;
678 				buf[len++] = ' ';
679 			}
680 			buf[len++] = ch;
681 		} else if (ch == '\t') {
682 			spaces_pending += tab_width - (len+spaces_pending)%tab_width;
683 		} else if (ch == '\b') {
684 			if (len)
685 				--len;
686 		}
687 	}
688 
689 	*lengthp = len;
690 	return (len > 0 || ch != EOF) ? buf : 0;
691 }
692 
693 /* (Re)allocate some memory, exiting with an error if we can't.
694  */
695 static void *
xrealloc(void * ptr,size_t nbytes)696 xrealloc(void *ptr, size_t nbytes)
697 {
698 	void *p;
699 
700 	p  = realloc(ptr, nbytes);
701 	if (p == NULL)
702 		errx(EX_OSERR, "out of memory");
703 	return p;
704 }
705 
706 void
usage(void)707 usage(void)
708 {
709 	extern char *__progname;
710 
711 	fprintf(stderr,
712 		"Usage:   %s [-cmps] [-d chars] [-l num] [-t num]\n"
713 		"             [-w width | -width | goal [maximum]] [file ...]\n"
714 		"Options: -c     center each line instead of formatting\n"
715 		"         -d <chars> double-space after <chars> at line end\n"
716 		"         -l <n> turn each <n> spaces at start of line into a tab\n"
717 		"         -m     try to make sure mail header lines stay separate\n"
718 		"         -n     format lines beginning with a dot\n"
719 		"         -p     allow indented paragraphs\n"
720 		"         -s     coalesce whitespace inside lines\n"
721 		"         -t <n> have tabs every <n> columns\n"
722 		"         -w <n> set maximum width to <n>\n"
723 		"         goal   set target width to goal\n", __progname);
724 	exit (1);
725 }
726