xref: /openbsd-src/usr.bin/fmt/fmt.c (revision c0cf38245a67f5252cbc7e0201952e8ab32772ea)
1*c0cf3824Sotto /*	$OpenBSD: fmt.c,v 1.39 2018/10/18 05:04:52 otto Exp $	*/
215576550Sschwarze /*
315576550Sschwarze  * This file is a derived work.
415576550Sschwarze  * The changes are covered by the following Copyright and license:
515576550Sschwarze  *
615576550Sschwarze  * Copyright (c) 2015, 2016 Ingo Schwarze <schwarze@openbsd.org>
715576550Sschwarze  * Copyright (c) 2000 Paul Janzen <pjanzen@foatdi.net>
815576550Sschwarze  *
915576550Sschwarze  * Permission to use, copy, modify, and distribute this software for any
1015576550Sschwarze  * purpose with or without fee is hereby granted, provided that the above
1115576550Sschwarze  * copyright notice and this permission notice appear in all copies.
1215576550Sschwarze  *
1315576550Sschwarze  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
1415576550Sschwarze  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
1515576550Sschwarze  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
1615576550Sschwarze  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
1715576550Sschwarze  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
1815576550Sschwarze  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
1915576550Sschwarze  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
2015576550Sschwarze  *
2115576550Sschwarze  *
2215576550Sschwarze  * The unchanged parts are covered by the following Copyright and license:
2315576550Sschwarze  *
2415576550Sschwarze  * Copyright (c) 1997 Gareth McCaughan. All rights reserved.
2515576550Sschwarze  *
2615576550Sschwarze  * Redistribution and use of this code, in source or binary forms,
2715576550Sschwarze  * with or without modification, are permitted subject to the following
2815576550Sschwarze  * conditions:
2915576550Sschwarze  *
3015576550Sschwarze  *  - Redistribution of source code must retain the above copyright
3115576550Sschwarze  *    notice, this list of conditions and the following disclaimer.
3215576550Sschwarze  *
3315576550Sschwarze  *  - If you distribute modified source code it must also include
3415576550Sschwarze  *    a notice saying that it has been modified, and giving a brief
3515576550Sschwarze  *    description of what changes have been made.
3615576550Sschwarze  *
3715576550Sschwarze  * Disclaimer: I am not responsible for the results of using this code.
3815576550Sschwarze  *             If it formats your hard disc, sends obscene messages to
3915576550Sschwarze  *             your boss and kills your children then that's your problem
4015576550Sschwarze  *             not mine. I give absolutely no warranty of any sort as to
4115576550Sschwarze  *             what the program will do, and absolutely refuse to be held
4215576550Sschwarze  *             liable for any consequences of your using it.
4315576550Sschwarze  *             Thank you. Have a nice day.
4415576550Sschwarze  *
4515576550Sschwarze  *
4615576550Sschwarze  * Brief overview of the changes made by OpenBSD:
4715576550Sschwarze  * Added UTF-8 support (2016).
4815576550Sschwarze  * Added pledge(2) support (2015).
4915576550Sschwarze  * ANSI function syntax and KNF (2004).
5015576550Sschwarze  * Added -w option (2000).
5115576550Sschwarze  * Some minor changes can be seen in the public OpenBSD CVS repository.
5215576550Sschwarze  */
53df930be7Sderaadt 
54dce78b8dSmillert /* Sensible version of fmt
55df930be7Sderaadt  *
56dce78b8dSmillert  * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ]
57dce78b8dSmillert  *
58dce78b8dSmillert  * Since the documentation for the original fmt is so poor, here
59dce78b8dSmillert  * is an accurate description of what this one does. It's usually
60dce78b8dSmillert  * the same. The *mechanism* used may differ from that suggested
61dce78b8dSmillert  * here. Note that we are *not* entirely compatible with fmt,
62dce78b8dSmillert  * because fmt gets so many things wrong.
63dce78b8dSmillert  *
64dce78b8dSmillert  * 1. Tabs are expanded, assuming 8-space tab stops.
65dce78b8dSmillert  *    If the `-t <n>' option is given, we assume <n>-space
66dce78b8dSmillert  *    tab stops instead.
67dce78b8dSmillert  *    Trailing blanks are removed from all lines.
68dce78b8dSmillert  *    x\b == nothing, for any x other than \b.
69dce78b8dSmillert  *    Other control characters are simply stripped. This
70dce78b8dSmillert  *    includes \r.
71dce78b8dSmillert  * 2. Each line is split into leading whitespace and
72dce78b8dSmillert  *    everything else. Maximal consecutive sequences of
73dce78b8dSmillert  *    lines with the same leading whitespace are considered
74dce78b8dSmillert  *    to form paragraphs, except that a blank line is always
75dce78b8dSmillert  *    a paragraph to itself.
76dce78b8dSmillert  *    If the `-p' option is given then the first line of a
77dce78b8dSmillert  *    paragraph is permitted to have indentation different
78dce78b8dSmillert  *    from that of the other lines.
79dce78b8dSmillert  *    If the `-m' option is given then a line that looks
80dce78b8dSmillert  *    like a mail message header, if it is not immediately
81dce78b8dSmillert  *    preceded by a non-blank non-message-header line, is
82dce78b8dSmillert  *    taken to start a new paragraph, which also contains
83dce78b8dSmillert  *    any subsequent lines with non-empty leading whitespace.
84ae00fe5fSmillert  *    Unless the `-n' option is given, lines beginning with
85ae00fe5fSmillert  *    a . (dot) are not formatted.
86dce78b8dSmillert  * 3. The "everything else" is split into words; a word
87dce78b8dSmillert  *    includes its trailing whitespace, and a word at the
88dce78b8dSmillert  *    end of a line is deemed to be followed by a single
89dce78b8dSmillert  *    space, or two spaces if it ends with a sentence-end
90dce78b8dSmillert  *    character. (See the `-d' option for how to change that.)
91dce78b8dSmillert  *    If the `-s' option has been given, then a word's trailing
92dce78b8dSmillert  *    whitespace is replaced by what it would have had if it
93dce78b8dSmillert  *    had occurred at end of line.
94dce78b8dSmillert  * 4. Each paragraph is sent to standard output as follows.
95dce78b8dSmillert  *    We output the leading whitespace, and then enough words
96dce78b8dSmillert  *    to make the line length as near as possible to the goal
97dce78b8dSmillert  *    without exceeding the maximum. (If a single word would
98dce78b8dSmillert  *    exceed the maximum, we output that anyway.) Of course
99dce78b8dSmillert  *    the trailing whitespace of the last word is ignored.
100dce78b8dSmillert  *    We then emit a newline and start again if there are any
101dce78b8dSmillert  *    words left.
102dce78b8dSmillert  *    Note that for a blank line this translates as "We emit
103dce78b8dSmillert  *    a newline".
104dce78b8dSmillert  *    If the `-l <n>' option is given, then leading whitespace
105dce78b8dSmillert  *    is modified slightly: <n> spaces are replaced by a tab.
106dce78b8dSmillert  *    Indented paragraphs (see above under `-p') make matters
107dce78b8dSmillert  *    more complicated than this suggests. Actually every paragraph
108dce78b8dSmillert  *    has two `leading whitespace' values; the value for the first
109dce78b8dSmillert  *    line, and the value for the most recent line. (While processing
110dce78b8dSmillert  *    the first line, the two are equal. When `-p' has not been
111dce78b8dSmillert  *    given, they are always equal.) The leading whitespace
112dce78b8dSmillert  *    actually output is that of the first line (for the first
113dce78b8dSmillert  *    line of *output*) or that of the most recent line (for
114dce78b8dSmillert  *    all other lines of output).
115dce78b8dSmillert  *    When `-m' has been given, message header paragraphs are
116dce78b8dSmillert  *    taken as having first-leading-whitespace empty and
117dce78b8dSmillert  *    subsequent-leading-whitespace two spaces.
118dce78b8dSmillert  *
119dce78b8dSmillert  * Multiple input files are formatted one at a time, so that a file
120dce78b8dSmillert  * never ends in the middle of a line.
121dce78b8dSmillert  *
122dce78b8dSmillert  * There's an alternative mode of operation, invoked by giving
123dce78b8dSmillert  * the `-c' option. In that case we just center every line,
124dce78b8dSmillert  * and most of the other options are ignored. This should
125dce78b8dSmillert  * really be in a separate program, but we must stay compatible
126dce78b8dSmillert  * with old `fmt'.
127dce78b8dSmillert  *
128dce78b8dSmillert  * QUERY: Should `-m' also try to do the right thing with quoted text?
129dce78b8dSmillert  * QUERY: `-b' to treat backslashed whitespace as old `fmt' does?
130dce78b8dSmillert  * QUERY: Option meaning `never join lines'?
131dce78b8dSmillert  * QUERY: Option meaning `split in mid-word to avoid overlong lines'?
132dce78b8dSmillert  * (Those last two might not be useful, since we have `fold'.)
133dce78b8dSmillert  *
134dce78b8dSmillert  * Differences from old `fmt':
135dce78b8dSmillert  *
136dce78b8dSmillert  *   - We have many more options. Options that aren't understood
137dce78b8dSmillert  *     generate a lengthy usage message, rather than being
138dce78b8dSmillert  *     treated as filenames.
139dce78b8dSmillert  *   - Even with `-m', our handling of message headers is
140dce78b8dSmillert  *     significantly different. (And much better.)
141dce78b8dSmillert  *   - We don't treat `\ ' as non-word-breaking.
142dce78b8dSmillert  *   - Downward changes of indentation start new paragraphs
143dce78b8dSmillert  *     for us, as well as upward. (I think old `fmt' behaves
144dce78b8dSmillert  *     in the way it does in order to allow indented paragraphs,
145dce78b8dSmillert  *     but this is a broken way of making indented paragraphs
146dce78b8dSmillert  *     behave right.)
147dce78b8dSmillert  *   - Given the choice of going over or under |goal_length|
148dce78b8dSmillert  *     by the same amount, we go over; old `fmt' goes under.
149dce78b8dSmillert  *   - We treat `?' as ending a sentence, and not `:'. Old `fmt'
150dce78b8dSmillert  *     does the reverse.
151dce78b8dSmillert  *   - We return approved return codes. Old `fmt' returns
152dce78b8dSmillert  *     1 for some errors, and *the number of unopenable files*
153dce78b8dSmillert  *     when that was all that went wrong.
154dce78b8dSmillert  *   - We have fewer crashes and more helpful error messages.
155dce78b8dSmillert  *   - We don't turn spaces into tabs at starts of lines unless
156dce78b8dSmillert  *     specifically requested.
157dce78b8dSmillert  *   - New `fmt' is somewhat smaller and slightly faster than
158dce78b8dSmillert  *     old `fmt'.
159dce78b8dSmillert  *
160dce78b8dSmillert  * Bugs:
161dce78b8dSmillert  *
162dce78b8dSmillert  *   None known. There probably are some, though.
163dce78b8dSmillert  *
164dce78b8dSmillert  * Portability:
165dce78b8dSmillert  *
166dce78b8dSmillert  *   I believe this code to be pretty portable. It does require
167dce78b8dSmillert  *   that you have `getopt'. If you need to include "getopt.h"
168dce78b8dSmillert  *   for this (e.g., if your system didn't come with `getopt'
169dce78b8dSmillert  *   and you installed it yourself) then you should arrange for
170dce78b8dSmillert  *   NEED_getopt_h to be #defined.
171dce78b8dSmillert  *
172dce78b8dSmillert  *   Everything here should work OK even on nasty 16-bit
173dce78b8dSmillert  *   machines and nice 64-bit ones. However, it's only really
174dce78b8dSmillert  *   been tested on my FreeBSD machine. Your mileage may vary.
175dce78b8dSmillert  */
176dce78b8dSmillert 
1773e58ca64Smillert #include <ctype.h>
17888d44a3eSmillert #include <err.h>
17988d44a3eSmillert #include <locale.h>
180df930be7Sderaadt #include <stdio.h>
181df930be7Sderaadt #include <stdlib.h>
182df930be7Sderaadt #include <string.h>
18388d44a3eSmillert #include <unistd.h>
184ef75aaf1Sschwarze #include <wchar.h>
185ef75aaf1Sschwarze #include <wctype.h>
1862e792abdSmillert 
187dce78b8dSmillert /* Something that, we hope, will never be a genuine line length,
188dce78b8dSmillert  * indentation etc.
189df930be7Sderaadt  */
190dce78b8dSmillert #define SILLY ((size_t)-1)
191df930be7Sderaadt 
192dce78b8dSmillert /* I used to use |strtoul| for this, but (1) not all systems have it
193dce78b8dSmillert  * and (2) it's probably better to use |strtol| to detect negative
194dce78b8dSmillert  * numbers better.
195dce78b8dSmillert  * If |fussyp==0| then we don't complain about non-numbers
196dce78b8dSmillert  * (returning 0 instead), but we do complain about bad numbers.
197df930be7Sderaadt  */
19888d44a3eSmillert static size_t
get_positive(const char * s,const char * err_mess,int fussyP)199bd4fa7f1Stedu get_positive(const char *s, const char *err_mess, int fussyP)
200bd4fa7f1Stedu {
201dce78b8dSmillert 	char *t;
202dce78b8dSmillert 	long result = strtol(s, &t, 0);
203bd4fa7f1Stedu 
204bd4fa7f1Stedu 	if (*t) {
205bd4fa7f1Stedu 		if (fussyP)
206bd4fa7f1Stedu 			goto Lose;
207bd4fa7f1Stedu 		else
208bd4fa7f1Stedu 			return 0;
209bd4fa7f1Stedu 	}
210bd4fa7f1Stedu 	if (result <= 0) {
211bd4fa7f1Stedu Lose:
21245942cd3Smillert 		errx(1, "%s", err_mess);
213bd4fa7f1Stedu 	}
214bd4fa7f1Stedu 
215dce78b8dSmillert 	return (size_t) result;
216df930be7Sderaadt }
217df930be7Sderaadt 
218dce78b8dSmillert /* Global variables */
2192e792abdSmillert 
220dce78b8dSmillert static int centerP = 0;				/* Try to center lines? */
221dce78b8dSmillert static size_t goal_length = 0;			/* Target length for output lines */
222dce78b8dSmillert static size_t max_length = 0;			/* Maximum length for output lines */
223dce78b8dSmillert static int coalesce_spaces_P = 0;		/* Coalesce multiple whitespace -> ' ' ? */
224dce78b8dSmillert static int allow_indented_paragraphs = 0;	/* Can first line have diff. ind.? */
225dce78b8dSmillert static int tab_width = 8;			/* Number of spaces per tab stop */
22688d44a3eSmillert static size_t output_tab_width = 0;		/* Ditto, when squashing leading spaces */
22788d44a3eSmillert static const char *sentence_enders = ".?!";	/* Double-space after these */
228dce78b8dSmillert static int grok_mail_headers = 0;		/* treat embedded mail headers magically? */
229ae00fe5fSmillert static int format_troff = 0;			/* Format troff? */
230df930be7Sderaadt 
2315ad508d7Sschwarze static int n_errors = 0;			/* Number of failed files. */
232dce78b8dSmillert static size_t x;				/* Horizontal position in output line */
233dce78b8dSmillert static size_t x0;				/* Ditto, ignoring leading whitespace */
234dce78b8dSmillert static size_t pending_spaces;			/* Spaces to add before next word */
235dce78b8dSmillert static int output_in_paragraph = 0;		/* Any of current para written out yet? */
236df930be7Sderaadt 
237dce78b8dSmillert /* Prototypes */
2383e58ca64Smillert 
239dce78b8dSmillert static void	process_named_file(const char *);
240dce78b8dSmillert static void	process_stream(FILE *, const char *);
241ef75aaf1Sschwarze static size_t	indent_length(const char *);
2426cd4fad2Sderaadt static int	might_be_header(const char *);
243ef75aaf1Sschwarze static void	new_paragraph(size_t);
244ef75aaf1Sschwarze static void	output_word(size_t, size_t, const char *, int, int, int);
245dce78b8dSmillert static void	output_indent(size_t);
246dce78b8dSmillert static void	center_stream(FILE *, const char *);
247ef75aaf1Sschwarze static char	*get_line(FILE *);
248*c0cf3824Sotto static void	*xreallocarray(void *, size_t, size_t);
249bd4fa7f1Stedu void		usage(void);
250df930be7Sderaadt 
25186106aaeSlum #define ERRS(x) (x >= 127 ? 127 : ++x)
252df930be7Sderaadt 
253dce78b8dSmillert /* Here is perhaps the right place to mention that this code is
254dce78b8dSmillert  * all in top-down order. Hence, |main| comes first.
255df930be7Sderaadt  */
2563e58ca64Smillert int
main(int argc,char * argv[])257bd4fa7f1Stedu main(int argc, char *argv[])
258bd4fa7f1Stedu {
259dce78b8dSmillert 	int ch;			/* used for |getopt| processing */
260df930be7Sderaadt 
26188d44a3eSmillert 	(void)setlocale(LC_CTYPE, "");
26288d44a3eSmillert 
2630bd1216cSderaadt 	if (pledge("stdio rpath", NULL) == -1)
2640bd1216cSderaadt 		err(1, "pledge");
265a0c49102Sderaadt 
266dce78b8dSmillert 	/* 1. Grok parameters. */
267bd4fa7f1Stedu 	while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) {
268518a5964Spjanzen 		switch (ch) {
269dce78b8dSmillert 		case 'c':
270dce78b8dSmillert 			centerP = 1;
271bd4fa7f1Stedu 			break;
272dce78b8dSmillert 		case 'd':
27388d44a3eSmillert 			sentence_enders = optarg;
274bd4fa7f1Stedu 			break;
275dce78b8dSmillert 		case 'l':
276dce78b8dSmillert 			output_tab_width
277dce78b8dSmillert 				= get_positive(optarg, "output tab width must be positive", 1);
278bd4fa7f1Stedu 			break;
279dce78b8dSmillert 		case 'm':
280dce78b8dSmillert 			grok_mail_headers = 1;
281bd4fa7f1Stedu 			break;
282ae00fe5fSmillert 		case 'n':
283ae00fe5fSmillert 			format_troff = 1;
284bd4fa7f1Stedu 			break;
285dce78b8dSmillert 		case 'p':
286dce78b8dSmillert 			allow_indented_paragraphs = 1;
287bd4fa7f1Stedu 			break;
288dce78b8dSmillert 		case 's':
289dce78b8dSmillert 			coalesce_spaces_P = 1;
290bd4fa7f1Stedu 			break;
291dce78b8dSmillert 		case 't':
292dce78b8dSmillert 			tab_width = get_positive(optarg, "tab width must be positive", 1);
293bd4fa7f1Stedu 			break;
294518a5964Spjanzen 		case 'w':
295518a5964Spjanzen 			goal_length = get_positive(optarg, "width must be positive", 1);
296518a5964Spjanzen 			max_length = goal_length;
297bd4fa7f1Stedu 			break;
298518a5964Spjanzen 		case '0': case '1': case '2': case '3': case '4': case '5':
299518a5964Spjanzen 		case '6': case '7': case '8': case '9':
300518a5964Spjanzen 			/* XXX  this is not a stylistically approved use of getopt() */
301518a5964Spjanzen 			if (goal_length == 0) {
302518a5964Spjanzen 				char *p;
303bd4fa7f1Stedu 
304518a5964Spjanzen 				p = argv[optind - 1];
305518a5964Spjanzen 				if (p[0] == '-' && p[1] == ch && !p[2])
306518a5964Spjanzen 					goal_length = get_positive(++p, "width must be nonzero", 1);
307518a5964Spjanzen 				else
308518a5964Spjanzen 					goal_length = get_positive(argv[optind]+1,
309518a5964Spjanzen 							"width must be nonzero", 1);
310518a5964Spjanzen 				max_length = goal_length;
311518a5964Spjanzen 			}
312bd4fa7f1Stedu 			break;
313bd4fa7f1Stedu 		case 'h':
314bd4fa7f1Stedu 		default:
315bd4fa7f1Stedu 			usage();
316bd4fa7f1Stedu 			/* NOT REACHED */
317dce78b8dSmillert 		}
318bd4fa7f1Stedu 	}
319bd4fa7f1Stedu 
320bd4fa7f1Stedu 	argc -= optind;
321bd4fa7f1Stedu 	argv += optind;
322dce78b8dSmillert 
323dce78b8dSmillert 	/* [ goal [ maximum ] ] */
324bd4fa7f1Stedu 	if (argc > 0 && goal_length == 0 &&
325bd4fa7f1Stedu 	    (goal_length = get_positive(*argv,"goal length must be positive", 0)) != 0) {
326bd4fa7f1Stedu 		--argc;
327bd4fa7f1Stedu 		++argv;
328bd4fa7f1Stedu 		if (argc > 0 && (max_length = get_positive(*argv,"max length must be positive", 0)) != 0) {
329bd4fa7f1Stedu 			--argc;
330bd4fa7f1Stedu 			++argv;
331dce78b8dSmillert 			if (max_length < goal_length)
33245942cd3Smillert 				errx(1, "max length must be >= goal length");
333dce78b8dSmillert 		}
334dce78b8dSmillert 	}
335bd4fa7f1Stedu 
336bd4fa7f1Stedu 	if (goal_length == 0)
337bd4fa7f1Stedu 		goal_length = 65;
338bd4fa7f1Stedu 	if (max_length == 0)
339bd4fa7f1Stedu 		max_length = goal_length+10;
340dce78b8dSmillert 
341dce78b8dSmillert 	/* 2. Process files. */
342dce78b8dSmillert 
343dce78b8dSmillert 	if (argc > 0) {
344bd4fa7f1Stedu 		while (argc-- > 0)
345bd4fa7f1Stedu 			process_named_file(*argv++);
346bd4fa7f1Stedu 	} else {
3470bd1216cSderaadt 		if (pledge("stdio", NULL) == -1)
3480bd1216cSderaadt 			err(1, "pledge");
349dce78b8dSmillert 		process_stream(stdin, "standard input");
350df930be7Sderaadt 	}
3512e792abdSmillert 
352dce78b8dSmillert 	/* We're done. */
35386106aaeSlum 	return n_errors;
3542e792abdSmillert 
355dce78b8dSmillert }
356dce78b8dSmillert 
357dce78b8dSmillert /* Process a single file, given its name.
358dce78b8dSmillert  */
359dce78b8dSmillert static void
process_named_file(const char * name)360bd4fa7f1Stedu process_named_file(const char *name)
361bd4fa7f1Stedu {
362bd4fa7f1Stedu 	FILE *f;
363bd4fa7f1Stedu 
364bd4fa7f1Stedu 	if ((f = fopen(name, "r")) == NULL) {
365f7fad249Scloder 		warn("%s", name);
36686106aaeSlum 		ERRS(n_errors);
367bd4fa7f1Stedu 	} else {
368dce78b8dSmillert 		process_stream(f, name);
369dce78b8dSmillert 		fclose(f);
370dce78b8dSmillert 	}
371dce78b8dSmillert }
372dce78b8dSmillert 
373dce78b8dSmillert /* Types of mail header continuation lines:
374dce78b8dSmillert  */
375dce78b8dSmillert typedef enum {
376dce78b8dSmillert 	hdr_ParagraphStart	= -1,
377dce78b8dSmillert 	hdr_NonHeader		= 0,
378dce78b8dSmillert 	hdr_Header		= 1,
379dce78b8dSmillert 	hdr_Continuation	= 2
380dce78b8dSmillert } HdrType;
381dce78b8dSmillert 
382dce78b8dSmillert /* Process a stream. This is where the real work happens,
383dce78b8dSmillert  * except that centering is handled separately.
384dce78b8dSmillert  */
385dce78b8dSmillert static void
process_stream(FILE * stream,const char * name)386bd4fa7f1Stedu process_stream(FILE *stream, const char *name)
387bd4fa7f1Stedu {
388ef75aaf1Sschwarze 	const char *wordp, *cp;
389ef75aaf1Sschwarze 	wchar_t wc;
390bd4fa7f1Stedu 	size_t np;
391dce78b8dSmillert 	size_t last_indent = SILLY;	/* how many spaces in last indent? */
392dce78b8dSmillert 	size_t para_line_number = 0;	/* how many lines already read in this para? */
393dce78b8dSmillert 	size_t first_indent = SILLY;	/* indentation of line 0 of paragraph */
394ef75aaf1Sschwarze 	int wcl;			/* number of bytes in wide character */
395ef75aaf1Sschwarze 	int wcw;			/* display width of wide character */
396ef75aaf1Sschwarze 	int word_length;		/* number of bytes in word */
397ef75aaf1Sschwarze 	int word_width;			/* display width of word */
398ef75aaf1Sschwarze 	int space_width;		/* display width of space after word */
399ef75aaf1Sschwarze 	int line_width;			/* display width of line */
400dce78b8dSmillert 	HdrType prev_header_type = hdr_ParagraphStart;
401bd4fa7f1Stedu 	HdrType header_type;
402bd4fa7f1Stedu 
403dce78b8dSmillert 	/* ^-- header_type of previous line; -1 at para start */
4046cd4fad2Sderaadt 	const char *line;
405dce78b8dSmillert 
406bd4fa7f1Stedu 	if (centerP) {
407bd4fa7f1Stedu 		center_stream(stream, name);
408bd4fa7f1Stedu 		return;
409bd4fa7f1Stedu 	}
410bd4fa7f1Stedu 
411ef75aaf1Sschwarze 	while ((line = get_line(stream)) != NULL) {
412ef75aaf1Sschwarze 		np = indent_length(line);
413bd4fa7f1Stedu 		header_type = hdr_NonHeader;
414dce78b8dSmillert 		if (grok_mail_headers && prev_header_type != hdr_NonHeader) {
415dce78b8dSmillert 			if (np == 0 && might_be_header(line))
416dce78b8dSmillert 				header_type = hdr_Header;
417dce78b8dSmillert 			else if (np > 0 && prev_header_type>hdr_NonHeader)
418dce78b8dSmillert 				header_type = hdr_Continuation;
419dce78b8dSmillert 		}
420bd4fa7f1Stedu 
421dce78b8dSmillert 		/* We need a new paragraph if and only if:
422dce78b8dSmillert 		 *   this line is blank,
423ae00fe5fSmillert 		 *   OR it's a troff request,
424dce78b8dSmillert 		 *   OR it's a mail header,
425dce78b8dSmillert 		 *   OR it's not a mail header AND the last line was one,
426dce78b8dSmillert 		 *   OR the indentation has changed
427dce78b8dSmillert 		 *      AND the line isn't a mail header continuation line
428dce78b8dSmillert 		 *      AND this isn't the second line of an indented paragraph.
429dce78b8dSmillert 		 */
430ef75aaf1Sschwarze 		if (*line == '\0' || (*line == '.' && !format_troff) ||
431bd4fa7f1Stedu 		    header_type == hdr_Header ||
432bd4fa7f1Stedu 		    (header_type == hdr_NonHeader && prev_header_type > hdr_NonHeader) ||
433bd4fa7f1Stedu 		    (np != last_indent && header_type != hdr_Continuation &&
434bd4fa7f1Stedu 		    (!allow_indented_paragraphs || para_line_number != 1)) ) {
435ef75aaf1Sschwarze 			new_paragraph(np);
436dce78b8dSmillert 			para_line_number = 0;
437dce78b8dSmillert 			first_indent = np;
438dce78b8dSmillert 			last_indent = np;
439bd4fa7f1Stedu 
440ae00fe5fSmillert 			/* nroff compatibility */
441ef75aaf1Sschwarze 			if (*line == '.' && !format_troff) {
442ef75aaf1Sschwarze 				puts(line);
443ae00fe5fSmillert 				continue;
444ae00fe5fSmillert 			}
445bd4fa7f1Stedu 			if (header_type == hdr_Header)
446bd4fa7f1Stedu 				last_indent = 2;	/* for cont. lines */
447ef75aaf1Sschwarze 			if (*line == '\0') {
448dce78b8dSmillert 				putchar('\n');
449dce78b8dSmillert 				prev_header_type = hdr_ParagraphStart;
450dce78b8dSmillert 				continue;
451bd4fa7f1Stedu 			} else {
452dce78b8dSmillert 				/* If this is an indented paragraph other than a mail header
453dce78b8dSmillert 				 * continuation, set |last_indent|.
454dce78b8dSmillert 				 */
455dce78b8dSmillert 				if (np != last_indent && header_type != hdr_Continuation)
456dce78b8dSmillert 					last_indent = np;
457dce78b8dSmillert 			}
458dce78b8dSmillert 			prev_header_type = header_type;
459dce78b8dSmillert 		}
460dce78b8dSmillert 
461ef75aaf1Sschwarze 		line_width = np;
462ef75aaf1Sschwarze 		for (wordp = line; *wordp != '\0'; wordp = cp) {
463ef75aaf1Sschwarze 			word_length = 0;
464ef75aaf1Sschwarze 			word_width = space_width = 0;
465ef75aaf1Sschwarze 			for (cp = wordp; *cp != '\0'; cp += wcl) {
466ef75aaf1Sschwarze 				wcl = mbtowc(&wc, cp, MB_CUR_MAX);
467ef75aaf1Sschwarze 				if (wcl == -1) {
468ef75aaf1Sschwarze 					(void)mbtowc(NULL, NULL, MB_CUR_MAX);
469ef75aaf1Sschwarze 					wc = L'?';
470ef75aaf1Sschwarze 					wcl = 1;
471ef75aaf1Sschwarze 					wcw = 1;
472ef75aaf1Sschwarze 				} else if (wc == L'\t')
473ef75aaf1Sschwarze 					wcw = (line_width / tab_width + 1) *
474ef75aaf1Sschwarze 					    tab_width - line_width;
475ef75aaf1Sschwarze 				else if ((wcw = wcwidth(wc)) == -1)
476ef75aaf1Sschwarze 					wcw = 1;
477332b6acdSschwarze 				if (iswblank(wc) && wc != 0xa0) {
478ef75aaf1Sschwarze 					/* Skip whitespace at start of line. */
479ef75aaf1Sschwarze 					if (word_length == 0) {
480ef75aaf1Sschwarze 						wordp += wcl;
481ef75aaf1Sschwarze 						continue;
482ef75aaf1Sschwarze 					}
483ef75aaf1Sschwarze 					/* Count whitespace after word. */
484ef75aaf1Sschwarze 					space_width += wcw;
485ef75aaf1Sschwarze 				} else {
486ef75aaf1Sschwarze 					/* Detect end of word. */
487ef75aaf1Sschwarze 					if (space_width > 0)
488ef75aaf1Sschwarze 						break;
489ef75aaf1Sschwarze 					/* Measure word. */
490ef75aaf1Sschwarze 					word_length += wcl;
491ef75aaf1Sschwarze 					word_width += wcw;
492ef75aaf1Sschwarze 				}
493ef75aaf1Sschwarze 				line_width += wcw;
494ef75aaf1Sschwarze 			}
495ef75aaf1Sschwarze 
496dce78b8dSmillert 			/* Send the word to the output machinery. */
497ef75aaf1Sschwarze 			output_word(first_indent, last_indent, wordp,
498ef75aaf1Sschwarze 			    word_length, word_width, space_width);
499dce78b8dSmillert 		}
500dce78b8dSmillert 		++para_line_number;
501dce78b8dSmillert 	}
502bd4fa7f1Stedu 
503ef75aaf1Sschwarze 	new_paragraph(0);
504bd4fa7f1Stedu 	if (ferror(stream)) {
505f7fad249Scloder 		warn("%s", name);
50686106aaeSlum 		ERRS(n_errors);
507bd4fa7f1Stedu 	}
508dce78b8dSmillert }
509dce78b8dSmillert 
510dce78b8dSmillert /* How long is the indent on this line?
511dce78b8dSmillert  */
512dce78b8dSmillert static size_t
indent_length(const char * line)513ef75aaf1Sschwarze indent_length(const char *line)
514bd4fa7f1Stedu {
515dce78b8dSmillert 	size_t n = 0;
516bd4fa7f1Stedu 
517ef75aaf1Sschwarze 	for (;;) {
518ef75aaf1Sschwarze 		switch(*line++) {
519ef75aaf1Sschwarze 		case ' ':
520bd4fa7f1Stedu 			++n;
521ef75aaf1Sschwarze 			continue;
522ef75aaf1Sschwarze 		case '\t':
523ef75aaf1Sschwarze 			n = (n / tab_width + 1) * tab_width;
524ef75aaf1Sschwarze 			continue;
525ef75aaf1Sschwarze 		default:
526ef75aaf1Sschwarze 			break;
527ef75aaf1Sschwarze 		}
528ef75aaf1Sschwarze 		break;
529ef75aaf1Sschwarze 	}
530dce78b8dSmillert 	return n;
531dce78b8dSmillert }
532dce78b8dSmillert 
533dce78b8dSmillert /* Might this line be a mail header?
534dce78b8dSmillert  * We deem a line to be a possible header if it matches the
535dce78b8dSmillert  * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
536dce78b8dSmillert  * as in RFC whatever-number-it-is; we want to be gratuitously
537dce78b8dSmillert  * conservative to avoid mangling ordinary civilised text.
538dce78b8dSmillert  */
539dce78b8dSmillert static int
might_be_header(const char * line)5406cd4fad2Sderaadt might_be_header(const char *line)
541bd4fa7f1Stedu {
542bd4fa7f1Stedu 
5436cd4fad2Sderaadt 	if (!isupper((unsigned char)*line++))
544bd4fa7f1Stedu 		return 0;
5456cd4fad2Sderaadt 	while (isalnum((unsigned char)*line) || *line == '-')
546bd4fa7f1Stedu 		++line;
5476cd4fad2Sderaadt 	return (*line == ':' && isspace((unsigned char)line[1]));
548dce78b8dSmillert }
549dce78b8dSmillert 
550dce78b8dSmillert /* Begin a new paragraph with an indent of |indent| spaces.
551dce78b8dSmillert  */
552dce78b8dSmillert static void
new_paragraph(size_t indent)553ef75aaf1Sschwarze new_paragraph(size_t indent)
554bd4fa7f1Stedu {
555bd4fa7f1Stedu 
556ef75aaf1Sschwarze 	if (x0 > 0)
557dce78b8dSmillert 		putchar('\n');
558bd4fa7f1Stedu 	x = indent;
559bd4fa7f1Stedu 	x0 = 0;
560bd4fa7f1Stedu 	pending_spaces = 0;
561dce78b8dSmillert 	output_in_paragraph = 0;
562dce78b8dSmillert }
563dce78b8dSmillert 
564dce78b8dSmillert /* Output spaces or tabs for leading indentation.
565dce78b8dSmillert  */
566dce78b8dSmillert static void
output_indent(size_t n_spaces)567bd4fa7f1Stedu output_indent(size_t n_spaces)
568bd4fa7f1Stedu {
569bd4fa7f1Stedu 
570ef75aaf1Sschwarze 	if (n_spaces == 0)
571ef75aaf1Sschwarze 		return;
572dce78b8dSmillert 	if (output_tab_width) {
573dce78b8dSmillert 		while (n_spaces >= output_tab_width) {
574dce78b8dSmillert 			putchar('\t');
575dce78b8dSmillert 			n_spaces -= output_tab_width;
576dce78b8dSmillert 		}
577dce78b8dSmillert 	}
578bd4fa7f1Stedu 	while (n_spaces-- > 0)
579bd4fa7f1Stedu 		putchar(' ');
580dce78b8dSmillert }
581dce78b8dSmillert 
582ef75aaf1Sschwarze /* Output a single word.
583dce78b8dSmillert  * indent0 and indent1 are the indents to use on the first and subsequent
584dce78b8dSmillert  * lines of a paragraph. They'll often be the same, of course.
585dce78b8dSmillert  */
586dce78b8dSmillert static void
output_word(size_t indent0,size_t indent1,const char * word,int length,int width,int spaces)587ef75aaf1Sschwarze output_word(size_t indent0, size_t indent1, const char *word,
588ef75aaf1Sschwarze     int length, int width, int spaces)
589bd4fa7f1Stedu {
590ef75aaf1Sschwarze 	size_t new_x = x + pending_spaces + width;
591dce78b8dSmillert 
592dce78b8dSmillert 	/* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
593dce78b8dSmillert 	 * (squashing internal whitespace), then add just one space;
594dce78b8dSmillert 	 * except that if the last character was a sentence-ender we
595dce78b8dSmillert 	 * actually add two spaces.
596dce78b8dSmillert 	 */
597dce78b8dSmillert 	if (coalesce_spaces_P || spaces == 0)
598dce78b8dSmillert 		spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1;
599dce78b8dSmillert 
600ef75aaf1Sschwarze 	if (x0 == 0)
601ef75aaf1Sschwarze 		output_indent(output_in_paragraph ? indent1 : indent0);
602ef75aaf1Sschwarze 	else if (new_x > max_length || x >= goal_length ||
603ef75aaf1Sschwarze 	    (new_x > goal_length && new_x-goal_length > goal_length-x)) {
604dce78b8dSmillert 		putchar('\n');
605ef75aaf1Sschwarze 		output_indent(indent1);
606bd4fa7f1Stedu 		x0 = 0;
607bd4fa7f1Stedu 		x = indent1;
608bd4fa7f1Stedu 	} else {
609ef75aaf1Sschwarze 		x0 += pending_spaces;
610ef75aaf1Sschwarze 		x += pending_spaces;
611ef75aaf1Sschwarze 		while (pending_spaces--)
612ef75aaf1Sschwarze 			putchar(' ');
613ef75aaf1Sschwarze 	}
614ef75aaf1Sschwarze 	x0 += width;
615ef75aaf1Sschwarze 	x += width;
616ef75aaf1Sschwarze 	while(length--)
617ef75aaf1Sschwarze 		putchar(*word++);
618bd4fa7f1Stedu 	pending_spaces = spaces;
619dce78b8dSmillert 	output_in_paragraph = 1;
620dce78b8dSmillert }
621dce78b8dSmillert 
622dce78b8dSmillert /* Process a stream, but just center its lines rather than trying to
623dce78b8dSmillert  * format them neatly.
624dce78b8dSmillert  */
625dce78b8dSmillert static void
center_stream(FILE * stream,const char * name)626bd4fa7f1Stedu center_stream(FILE *stream, const char *name)
627bd4fa7f1Stedu {
628b22b812bSschwarze 	char *line, *cp;
629b22b812bSschwarze 	wchar_t wc;
630b22b812bSschwarze 	size_t l;	/* Display width of the line. */
631b22b812bSschwarze 	int wcw;	/* Display width of one character. */
632b22b812bSschwarze 	int wcl;	/* Length in bytes of one character. */
633bd4fa7f1Stedu 
634ef75aaf1Sschwarze 	while ((line = get_line(stream)) != NULL) {
635b22b812bSschwarze 		l = 0;
636b22b812bSschwarze 		for (cp = line; *cp != '\0'; cp += wcl) {
637b22b812bSschwarze 			if (*cp == '\t')
638b22b812bSschwarze 				*cp = ' ';
639b22b812bSschwarze 			if ((wcl = mbtowc(&wc, cp, MB_CUR_MAX)) == -1) {
640b22b812bSschwarze 				(void)mbtowc(NULL, NULL, MB_CUR_MAX);
641b22b812bSschwarze 				*cp = '?';
642b22b812bSschwarze 				wcl = 1;
643b22b812bSschwarze 				wcw = 1;
644b22b812bSschwarze 			} else if ((wcw = wcwidth(wc)) == -1)
645b22b812bSschwarze 				wcw = 1;
646b22b812bSschwarze 			if (l == 0 && iswspace(wc))
647b22b812bSschwarze 				line += wcl;
648b22b812bSschwarze 			else
649b22b812bSschwarze 				l += wcw;
650b22b812bSschwarze 		}
651bd4fa7f1Stedu 		while (l < goal_length) {
652bd4fa7f1Stedu 			putchar(' ');
653bd4fa7f1Stedu 			l += 2;
654bd4fa7f1Stedu 		}
655ef75aaf1Sschwarze 		puts(line);
656dce78b8dSmillert 	}
657bd4fa7f1Stedu 
658bd4fa7f1Stedu 	if (ferror(stream)) {
659f7fad249Scloder 		warn("%s", name);
66086106aaeSlum 		ERRS(n_errors);
661bd4fa7f1Stedu 	}
662dce78b8dSmillert }
663dce78b8dSmillert 
664ef75aaf1Sschwarze /* Get a single line from a stream.  Strip control
665dce78b8dSmillert  * characters and trailing whitespace, and handle backspaces.
666ef75aaf1Sschwarze  * Return the address of the buffer containing the line.
667dce78b8dSmillert  * This can cope with arbitrarily long lines, and with lines
668dce78b8dSmillert  * without terminating \n.
669dce78b8dSmillert  * If there are no characters left or an error happens, we
670ef75aaf1Sschwarze  * return NULL.
671dce78b8dSmillert  */
672dce78b8dSmillert static char *
get_line(FILE * stream)673ef75aaf1Sschwarze get_line(FILE *stream)
674bd4fa7f1Stedu {
675bd4fa7f1Stedu 	int ch;
676bd4fa7f1Stedu 	int troff = 0;
677dce78b8dSmillert 	static char *buf = NULL;
678dce78b8dSmillert 	static size_t length = 0;
679dce78b8dSmillert 	size_t len = 0;
680dce78b8dSmillert 
681bd4fa7f1Stedu 	if (buf == NULL) {
682bd4fa7f1Stedu 		length = 100;
683*c0cf3824Sotto 		buf = xreallocarray(NULL, length, 1);
684bd4fa7f1Stedu 	}
685bd4fa7f1Stedu 
686dce78b8dSmillert 	while ((ch = getc(stream)) != '\n' && ch != EOF) {
687ef75aaf1Sschwarze 		if ((len == 0) && (ch == '.' && !format_troff))
688bd4fa7f1Stedu 			troff = 1;
689ef75aaf1Sschwarze 		if (troff || ch == '\t' || !iscntrl(ch)) {
690*c0cf3824Sotto 			if (len >= length - 1) {
691*c0cf3824Sotto 				buf = xreallocarray(buf, length, 2);
692bd4fa7f1Stedu 				length *= 2;
693dce78b8dSmillert 			}
694dce78b8dSmillert 			buf[len++] = ch;
695bd4fa7f1Stedu 		} else if (ch == '\b') {
696bd4fa7f1Stedu 			if (len)
697bd4fa7f1Stedu 				--len;
698dce78b8dSmillert 		}
699bd4fa7f1Stedu 	}
700ef75aaf1Sschwarze 	while (len > 0 && isspace((unsigned char)buf[len-1]))
701ef75aaf1Sschwarze 		--len;
702ef75aaf1Sschwarze 	buf[len] = '\0';
703ef75aaf1Sschwarze 	return (len > 0 || ch != EOF) ? buf : NULL;
704dce78b8dSmillert }
705dce78b8dSmillert 
706dce78b8dSmillert /* (Re)allocate some memory, exiting with an error if we can't.
707dce78b8dSmillert  */
708dce78b8dSmillert static void *
xreallocarray(void * ptr,size_t nmemb,size_t size)709*c0cf3824Sotto xreallocarray(void *ptr, size_t nmemb, size_t size)
710bd4fa7f1Stedu {
711bd4fa7f1Stedu 	void *p;
712bd4fa7f1Stedu 
713*c0cf3824Sotto 	p  = reallocarray(ptr, nmemb, size);
714bd4fa7f1Stedu 	if (p == NULL)
71545942cd3Smillert 		errx(1, "out of memory");
716dce78b8dSmillert 	return p;
7172e792abdSmillert }
718bd4fa7f1Stedu 
719bd4fa7f1Stedu void
usage(void)720bd4fa7f1Stedu usage(void)
721bd4fa7f1Stedu {
7227e985d25Smickey 	extern char *__progname;
723bd4fa7f1Stedu 
724bd4fa7f1Stedu 	fprintf(stderr,
725fa5c53eeSjmc 		"usage: %s [-cmnps] [-d chars] [-l number] [-t number]\n"
726fa5c53eeSjmc 		"\t[goal [maximum] | -width | -w width] [file ...]\n",
727fa5c53eeSjmc 			__progname);
7287e985d25Smickey 	exit (1);
729bd4fa7f1Stedu }
730