xref: /freebsd/usr.bin/fmt/fmt.c (revision 074e77e66eb40fe39c97f323b157c99e7e828750)
186aba0f2SPedro F. Giffuni /*	$OpenBSD: fmt.c,v 1.21 2004/04/01 23:14:19 tedu Exp $	*/
21438aefcSRuslan Ermilov 
31438aefcSRuslan Ermilov /* Sensible version of fmt
49b50d902SRodney W. Grimes  *
51438aefcSRuslan Ermilov  * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ]
61438aefcSRuslan Ermilov  *
71438aefcSRuslan Ermilov  * Since the documentation for the original fmt is so poor, here
81438aefcSRuslan Ermilov  * is an accurate description of what this one does. It's usually
91438aefcSRuslan Ermilov  * the same. The *mechanism* used may differ from that suggested
101438aefcSRuslan Ermilov  * here. Note that we are *not* entirely compatible with fmt,
111438aefcSRuslan Ermilov  * because fmt gets so many things wrong.
121438aefcSRuslan Ermilov  *
131438aefcSRuslan Ermilov  * 1. Tabs are expanded, assuming 8-space tab stops.
141438aefcSRuslan Ermilov  *    If the `-t <n>' option is given, we assume <n>-space
151438aefcSRuslan Ermilov  *    tab stops instead.
161438aefcSRuslan Ermilov  *    Trailing blanks are removed from all lines.
171438aefcSRuslan Ermilov  *    x\b == nothing, for any x other than \b.
181438aefcSRuslan Ermilov  *    Other control characters are simply stripped. This
191438aefcSRuslan Ermilov  *    includes \r.
201438aefcSRuslan Ermilov  * 2. Each line is split into leading whitespace and
211438aefcSRuslan Ermilov  *    everything else. Maximal consecutive sequences of
221438aefcSRuslan Ermilov  *    lines with the same leading whitespace are considered
231438aefcSRuslan Ermilov  *    to form paragraphs, except that a blank line is always
241438aefcSRuslan Ermilov  *    a paragraph to itself.
251438aefcSRuslan Ermilov  *    If the `-p' option is given then the first line of a
261438aefcSRuslan Ermilov  *    paragraph is permitted to have indentation different
271438aefcSRuslan Ermilov  *    from that of the other lines.
281438aefcSRuslan Ermilov  *    If the `-m' option is given then a line that looks
291438aefcSRuslan Ermilov  *    like a mail message header, if it is not immediately
301438aefcSRuslan Ermilov  *    preceded by a non-blank non-message-header line, is
311438aefcSRuslan Ermilov  *    taken to start a new paragraph, which also contains
321438aefcSRuslan Ermilov  *    any subsequent lines with non-empty leading whitespace.
33deba2451SRuslan Ermilov  *    Unless the `-n' option is given, lines beginning with
34deba2451SRuslan Ermilov  *    a . (dot) are not formatted.
351438aefcSRuslan Ermilov  * 3. The "everything else" is split into words; a word
361438aefcSRuslan Ermilov  *    includes its trailing whitespace, and a word at the
371438aefcSRuslan Ermilov  *    end of a line is deemed to be followed by a single
381438aefcSRuslan Ermilov  *    space, or two spaces if it ends with a sentence-end
391438aefcSRuslan Ermilov  *    character. (See the `-d' option for how to change that.)
401438aefcSRuslan Ermilov  *    If the `-s' option has been given, then a word's trailing
411438aefcSRuslan Ermilov  *    whitespace is replaced by what it would have had if it
421438aefcSRuslan Ermilov  *    had occurred at end of line.
431438aefcSRuslan Ermilov  * 4. Each paragraph is sent to standard output as follows.
441438aefcSRuslan Ermilov  *    We output the leading whitespace, and then enough words
451438aefcSRuslan Ermilov  *    to make the line length as near as possible to the goal
461438aefcSRuslan Ermilov  *    without exceeding the maximum. (If a single word would
471438aefcSRuslan Ermilov  *    exceed the maximum, we output that anyway.) Of course
481438aefcSRuslan Ermilov  *    the trailing whitespace of the last word is ignored.
491438aefcSRuslan Ermilov  *    We then emit a newline and start again if there are any
501438aefcSRuslan Ermilov  *    words left.
511438aefcSRuslan Ermilov  *    Note that for a blank line this translates as "We emit
521438aefcSRuslan Ermilov  *    a newline".
531438aefcSRuslan Ermilov  *    If the `-l <n>' option is given, then leading whitespace
541438aefcSRuslan Ermilov  *    is modified slightly: <n> spaces are replaced by a tab.
551438aefcSRuslan Ermilov  *    Indented paragraphs (see above under `-p') make matters
561438aefcSRuslan Ermilov  *    more complicated than this suggests. Actually every paragraph
571438aefcSRuslan Ermilov  *    has two `leading whitespace' values; the value for the first
581438aefcSRuslan Ermilov  *    line, and the value for the most recent line. (While processing
591438aefcSRuslan Ermilov  *    the first line, the two are equal. When `-p' has not been
601438aefcSRuslan Ermilov  *    given, they are always equal.) The leading whitespace
611438aefcSRuslan Ermilov  *    actually output is that of the first line (for the first
621438aefcSRuslan Ermilov  *    line of *output*) or that of the most recent line (for
631438aefcSRuslan Ermilov  *    all other lines of output).
641438aefcSRuslan Ermilov  *    When `-m' has been given, message header paragraphs are
651438aefcSRuslan Ermilov  *    taken as having first-leading-whitespace empty and
661438aefcSRuslan Ermilov  *    subsequent-leading-whitespace two spaces.
671438aefcSRuslan Ermilov  *
681438aefcSRuslan Ermilov  * Multiple input files are formatted one at a time, so that a file
691438aefcSRuslan Ermilov  * never ends in the middle of a line.
701438aefcSRuslan Ermilov  *
711438aefcSRuslan Ermilov  * There's an alternative mode of operation, invoked by giving
721438aefcSRuslan Ermilov  * the `-c' option. In that case we just center every line,
731438aefcSRuslan Ermilov  * and most of the other options are ignored. This should
741438aefcSRuslan Ermilov  * really be in a separate program, but we must stay compatible
751438aefcSRuslan Ermilov  * with old `fmt'.
761438aefcSRuslan Ermilov  *
771438aefcSRuslan Ermilov  * QUERY: Should `-m' also try to do the right thing with quoted text?
781438aefcSRuslan Ermilov  * QUERY: `-b' to treat backslashed whitespace as old `fmt' does?
791438aefcSRuslan Ermilov  * QUERY: Option meaning `never join lines'?
801438aefcSRuslan Ermilov  * QUERY: Option meaning `split in mid-word to avoid overlong lines'?
811438aefcSRuslan Ermilov  * (Those last two might not be useful, since we have `fold'.)
821438aefcSRuslan Ermilov  *
831438aefcSRuslan Ermilov  * Differences from old `fmt':
841438aefcSRuslan Ermilov  *
851438aefcSRuslan Ermilov  *   - We have many more options. Options that aren't understood
861438aefcSRuslan Ermilov  *     generate a lengthy usage message, rather than being
871438aefcSRuslan Ermilov  *     treated as filenames.
881438aefcSRuslan Ermilov  *   - Even with `-m', our handling of message headers is
891438aefcSRuslan Ermilov  *     significantly different. (And much better.)
901438aefcSRuslan Ermilov  *   - We don't treat `\ ' as non-word-breaking.
911438aefcSRuslan Ermilov  *   - Downward changes of indentation start new paragraphs
921438aefcSRuslan Ermilov  *     for us, as well as upward. (I think old `fmt' behaves
931438aefcSRuslan Ermilov  *     in the way it does in order to allow indented paragraphs,
941438aefcSRuslan Ermilov  *     but this is a broken way of making indented paragraphs
951438aefcSRuslan Ermilov  *     behave right.)
961438aefcSRuslan Ermilov  *   - Given the choice of going over or under |goal_length|
971438aefcSRuslan Ermilov  *     by the same amount, we go over; old `fmt' goes under.
981438aefcSRuslan Ermilov  *   - We treat `?' as ending a sentence, and not `:'. Old `fmt'
991438aefcSRuslan Ermilov  *     does the reverse.
1001438aefcSRuslan Ermilov  *   - We return approved return codes. Old `fmt' returns
1011438aefcSRuslan Ermilov  *     1 for some errors, and *the number of unopenable files*
1021438aefcSRuslan Ermilov  *     when that was all that went wrong.
1031438aefcSRuslan Ermilov  *   - We have fewer crashes and more helpful error messages.
1041438aefcSRuslan Ermilov  *   - We don't turn spaces into tabs at starts of lines unless
1051438aefcSRuslan Ermilov  *     specifically requested.
1061438aefcSRuslan Ermilov  *   - New `fmt' is somewhat smaller and slightly faster than
1071438aefcSRuslan Ermilov  *     old `fmt'.
1081438aefcSRuslan Ermilov  *
1091438aefcSRuslan Ermilov  * Bugs:
1101438aefcSRuslan Ermilov  *
1111438aefcSRuslan Ermilov  *   None known. There probably are some, though.
1121438aefcSRuslan Ermilov  *
1131438aefcSRuslan Ermilov  * Portability:
1141438aefcSRuslan Ermilov  *
1151438aefcSRuslan Ermilov  *   I believe this code to be pretty portable. It does require
1161438aefcSRuslan Ermilov  *   that you have `getopt'. If you need to include "getopt.h"
1171438aefcSRuslan Ermilov  *   for this (e.g., if your system didn't come with `getopt'
1181438aefcSRuslan Ermilov  *   and you installed it yourself) then you should arrange for
1191438aefcSRuslan Ermilov  *   NEED_getopt_h to be #defined.
1201438aefcSRuslan Ermilov  *
1211438aefcSRuslan Ermilov  *   Everything here should work OK even on nasty 16-bit
1221438aefcSRuslan Ermilov  *   machines and nice 64-bit ones. However, it's only really
1231438aefcSRuslan Ermilov  *   been tested on my FreeBSD machine. Your mileage may vary.
1241438aefcSRuslan Ermilov  */
1251438aefcSRuslan Ermilov 
1261438aefcSRuslan Ermilov /* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
1271438aefcSRuslan Ermilov  *
1281438aefcSRuslan Ermilov  * Redistribution and use of this code, in source or binary forms,
1291438aefcSRuslan Ermilov  * with or without modification, are permitted subject to the following
1301438aefcSRuslan Ermilov  * conditions:
1311438aefcSRuslan Ermilov  *
1321438aefcSRuslan Ermilov  *  - Redistribution of source code must retain the above copyright
1339b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
1349b50d902SRodney W. Grimes  *
1351438aefcSRuslan Ermilov  *  - If you distribute modified source code it must also include
1361438aefcSRuslan Ermilov  *    a notice saying that it has been modified, and giving a brief
1371438aefcSRuslan Ermilov  *    description of what changes have been made.
1381438aefcSRuslan Ermilov  *
1391438aefcSRuslan Ermilov  * Disclaimer: I am not responsible for the results of using this code.
1401438aefcSRuslan Ermilov  *             If it formats your hard disc, sends obscene messages to
1411438aefcSRuslan Ermilov  *             your boss and kills your children then that's your problem
1421438aefcSRuslan Ermilov  *             not mine. I give absolutely no warranty of any sort as to
1431438aefcSRuslan Ermilov  *             what the program will do, and absolutely refuse to be held
1441438aefcSRuslan Ermilov  *             liable for any consequences of your using it.
1451438aefcSRuslan Ermilov  *             Thank you. Have a nice day.
1461438aefcSRuslan Ermilov  */
1471438aefcSRuslan Ermilov 
1481438aefcSRuslan Ermilov /* RCS change log:
1491438aefcSRuslan Ermilov  * Revision 1.5  1998/03/02 18:02:21  gjm11
1501438aefcSRuslan Ermilov  * Minor changes for portability.
1511438aefcSRuslan Ermilov  *
1521438aefcSRuslan Ermilov  * Revision 1.4  1997/10/01 11:51:28  gjm11
1531438aefcSRuslan Ermilov  * Repair broken indented-paragraph handling.
1541438aefcSRuslan Ermilov  * Add mail message header stuff.
1551438aefcSRuslan Ermilov  * Improve comments and layout.
1561438aefcSRuslan Ermilov  * Make usable with non-BSD systems.
1571438aefcSRuslan Ermilov  * Add revision display to usage message.
1581438aefcSRuslan Ermilov  *
1591438aefcSRuslan Ermilov  * Revision 1.3  1997/09/30 16:24:47  gjm11
1601438aefcSRuslan Ermilov  * Add copyright notice, rcsid string and log message.
1611438aefcSRuslan Ermilov  *
1621438aefcSRuslan Ermilov  * Revision 1.2  1997/09/30 16:13:39  gjm11
1631438aefcSRuslan Ermilov  * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h .
1641438aefcSRuslan Ermilov  * Parse options with `getopt'. Clean up code generally.
1651438aefcSRuslan Ermilov  * Make comments more accurate.
1661438aefcSRuslan Ermilov  *
1671438aefcSRuslan Ermilov  * Revision 1.1  1997/09/30 11:29:57  gjm11
1681438aefcSRuslan Ermilov  * Initial revision
1699b50d902SRodney W. Grimes  */
1709b50d902SRodney W. Grimes 
1719b50d902SRodney W. Grimes #ifndef lint
1721438aefcSRuslan Ermilov static const char copyright[] =
1731438aefcSRuslan Ermilov "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n";
1749b50d902SRodney W. Grimes #endif	/* not lint */
175e026a48cSDavid E. O'Brien #include <sys/cdefs.h>
176e026a48cSDavid E. O'Brien __FBSDID("$FreeBSD$");
1779b50d902SRodney W. Grimes 
17863ffb113SPhilippe Charnier #include <err.h>
179a2229407SJuli Mallett #include <limits.h>
1808bbd9072SAndrey A. Chernov #include <locale.h>
18163ffb113SPhilippe Charnier #include <stdio.h>
182e6c267f1SJoerg Wunsch #include <stdlib.h>
183821df508SXin LI #include <string.h>
1841438aefcSRuslan Ermilov #include <sysexits.h>
1851438aefcSRuslan Ermilov #include <unistd.h>
18628d92b74STim J. Robbins #include <wchar.h>
18728d92b74STim J. Robbins #include <wctype.h>
1889b50d902SRodney W. Grimes 
1891438aefcSRuslan Ermilov /* Something that, we hope, will never be a genuine line length,
1901438aefcSRuslan Ermilov  * indentation etc.
1919b50d902SRodney W. Grimes  */
1921438aefcSRuslan Ermilov #define SILLY ((size_t)-1)
1939b50d902SRodney W. Grimes 
1941438aefcSRuslan Ermilov /* I used to use |strtoul| for this, but (1) not all systems have it
1951438aefcSRuslan Ermilov  * and (2) it's probably better to use |strtol| to detect negative
1961438aefcSRuslan Ermilov  * numbers better.
1971438aefcSRuslan Ermilov  * If |fussyp==0| then we don't complain about non-numbers
1981438aefcSRuslan Ermilov  * (returning 0 instead), but we do complain about bad numbers.
1999b50d902SRodney W. Grimes  */
2001438aefcSRuslan Ermilov static size_t
20186aba0f2SPedro F. Giffuni get_positive(const char *s, const char *err_mess, int fussyP)
20286aba0f2SPedro F. Giffuni {
2031438aefcSRuslan Ermilov 	char *t;
2041438aefcSRuslan Ermilov 	long result = strtol(s, &t, 0);
20586aba0f2SPedro F. Giffuni 
20686aba0f2SPedro F. Giffuni 	if (*t) {
20786aba0f2SPedro F. Giffuni 		if (fussyP)
20886aba0f2SPedro F. Giffuni 			goto Lose;
20986aba0f2SPedro F. Giffuni 		else
21086aba0f2SPedro F. Giffuni 			return 0;
21186aba0f2SPedro F. Giffuni 	}
21286aba0f2SPedro F. Giffuni 	if (result <= 0) {
21386aba0f2SPedro F. Giffuni Lose:		errx(EX_USAGE, "%s", err_mess);
21486aba0f2SPedro F. Giffuni 	}
2151438aefcSRuslan Ermilov 	return (size_t)result;
2161438aefcSRuslan Ermilov }
2179b50d902SRodney W. Grimes 
218ccb8bea4SRuslan Ermilov static size_t
21986aba0f2SPedro F. Giffuni get_nonnegative(const char *s, const char *err_mess, int fussyP)
22086aba0f2SPedro F. Giffuni {
221ccb8bea4SRuslan Ermilov 	char *t;
222ccb8bea4SRuslan Ermilov 	long result = strtol(s, &t, 0);
22386aba0f2SPedro F. Giffuni 
22486aba0f2SPedro F. Giffuni 	if (*t) {
22586aba0f2SPedro F. Giffuni 		if (fussyP)
22686aba0f2SPedro F. Giffuni 			goto Lose;
22786aba0f2SPedro F. Giffuni 		else
22886aba0f2SPedro F. Giffuni 			return 0;
22986aba0f2SPedro F. Giffuni 	}
23086aba0f2SPedro F. Giffuni 	if (result < 0) {
23186aba0f2SPedro F. Giffuni Lose:		errx(EX_USAGE, "%s", err_mess);
23286aba0f2SPedro F. Giffuni 	}
233ccb8bea4SRuslan Ermilov 	return (size_t)result;
234ccb8bea4SRuslan Ermilov }
235ccb8bea4SRuslan Ermilov 
2361438aefcSRuslan Ermilov /* Global variables */
2379b50d902SRodney W. Grimes 
2381438aefcSRuslan Ermilov static int centerP = 0;			/* Try to center lines? */
2391438aefcSRuslan Ermilov static size_t goal_length = 0;		/* Target length for output lines */
2401438aefcSRuslan Ermilov static size_t max_length = 0;		/* Maximum length for output lines */
2411438aefcSRuslan Ermilov static int coalesce_spaces_P = 0;	/* Coalesce multiple whitespace -> ' ' ? */
2421438aefcSRuslan Ermilov static int allow_indented_paragraphs = 0;	/* Can first line have diff. ind.? */
2431438aefcSRuslan Ermilov static int tab_width = 8;		/* Number of spaces per tab stop */
244ccb8bea4SRuslan Ermilov static size_t output_tab_width = 8;	/* Ditto, when squashing leading spaces */
24528d92b74STim J. Robbins static const wchar_t *sentence_enders = L".?!";	/* Double-space after these */
2461438aefcSRuslan Ermilov static int grok_mail_headers = 0;	/* treat embedded mail headers magically? */
247deba2451SRuslan Ermilov static int format_troff = 0;		/* Format troff? */
2489b50d902SRodney W. Grimes 
2491438aefcSRuslan Ermilov static int n_errors = 0;		/* Number of failed files. Return on exit. */
250*074e77e6SPedro F. Giffuni static wchar_t *output_buffer = NULL;	/* Output line will be built here */
2511438aefcSRuslan Ermilov static size_t x;			/* Horizontal position in output line */
2521438aefcSRuslan Ermilov static size_t x0;			/* Ditto, ignoring leading whitespace */
25328d92b74STim J. Robbins static size_t output_buffer_length = 0;
2541438aefcSRuslan Ermilov static size_t pending_spaces;		/* Spaces to add before next word */
2551438aefcSRuslan Ermilov static int output_in_paragraph = 0;	/* Any of current para written out yet? */
25663ffb113SPhilippe Charnier 
2571438aefcSRuslan Ermilov /* Prototypes */
2581438aefcSRuslan Ermilov 
2591438aefcSRuslan Ermilov static void process_named_file(const char *);
2601438aefcSRuslan Ermilov static void process_stream(FILE *, const char *);
26128d92b74STim J. Robbins static size_t indent_length(const wchar_t *, size_t);
26228d92b74STim J. Robbins static int might_be_header(const wchar_t *);
2631438aefcSRuslan Ermilov static void new_paragraph(size_t, size_t);
26486aba0f2SPedro F. Giffuni static void output_word(size_t, size_t, const wchar_t *, size_t, size_t);
2651438aefcSRuslan Ermilov static void output_indent(size_t);
2661438aefcSRuslan Ermilov static void center_stream(FILE *, const char *);
26728d92b74STim J. Robbins static wchar_t *get_line(FILE *, size_t *);
2681438aefcSRuslan Ermilov static void *xrealloc(void *, size_t);
2691438aefcSRuslan Ermilov 
2701438aefcSRuslan Ermilov #define XMALLOC(x) xrealloc(0,x)
2711438aefcSRuslan Ermilov 
2721438aefcSRuslan Ermilov /* Here is perhaps the right place to mention that this code is
2731438aefcSRuslan Ermilov  * all in top-down order. Hence, |main| comes first.
2749b50d902SRodney W. Grimes  */
27563ffb113SPhilippe Charnier int
27686aba0f2SPedro F. Giffuni main(int argc, char *argv[])
27786aba0f2SPedro F. Giffuni {
2781438aefcSRuslan Ermilov 	int ch;				/* used for |getopt| processing */
27928d92b74STim J. Robbins 	wchar_t *tmp;
28028d92b74STim J. Robbins 	size_t len;
28128d92b74STim J. Robbins 	const char *src;
2829b50d902SRodney W. Grimes 
2838bbd9072SAndrey A. Chernov 	(void)setlocale(LC_CTYPE, "");
2848bbd9072SAndrey A. Chernov 
2851438aefcSRuslan Ermilov 	/* 1. Grok parameters. */
2861438aefcSRuslan Ermilov 
287deba2451SRuslan Ermilov 	while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1)
2881438aefcSRuslan Ermilov 		switch (ch) {
2891438aefcSRuslan Ermilov 		case 'c':
2901438aefcSRuslan Ermilov 			centerP = 1;
291deba2451SRuslan Ermilov 			format_troff = 1;
2921438aefcSRuslan Ermilov 			continue;
2931438aefcSRuslan Ermilov 		case 'd':
29428d92b74STim J. Robbins 			src = optarg;
29528d92b74STim J. Robbins 			len = mbsrtowcs(NULL, &src, 0, NULL);
29628d92b74STim J. Robbins 			if (len == (size_t)-1)
29728d92b74STim J. Robbins 				err(EX_USAGE, "bad sentence-ending character set");
29828d92b74STim J. Robbins 			tmp = XMALLOC((len + 1) * sizeof(wchar_t));
29928d92b74STim J. Robbins 			mbsrtowcs(tmp, &src, len + 1, NULL);
30028d92b74STim J. Robbins 			sentence_enders = tmp;
3011438aefcSRuslan Ermilov 			continue;
3021438aefcSRuslan Ermilov 		case 'l':
3031438aefcSRuslan Ermilov 			output_tab_width
304ccb8bea4SRuslan Ermilov 			    = get_nonnegative(optarg, "output tab width must be non-negative", 1);
3051438aefcSRuslan Ermilov 			continue;
3061438aefcSRuslan Ermilov 		case 'm':
3071438aefcSRuslan Ermilov 			grok_mail_headers = 1;
3081438aefcSRuslan Ermilov 			continue;
309deba2451SRuslan Ermilov 		case 'n':
310deba2451SRuslan Ermilov 			format_troff = 1;
311deba2451SRuslan Ermilov 			continue;
3121438aefcSRuslan Ermilov 		case 'p':
3131438aefcSRuslan Ermilov 			allow_indented_paragraphs = 1;
3141438aefcSRuslan Ermilov 			continue;
3151438aefcSRuslan Ermilov 		case 's':
3161438aefcSRuslan Ermilov 			coalesce_spaces_P = 1;
3171438aefcSRuslan Ermilov 			continue;
3181438aefcSRuslan Ermilov 		case 't':
3191438aefcSRuslan Ermilov 			tab_width = get_positive(optarg, "tab width must be positive", 1);
3201438aefcSRuslan Ermilov 			continue;
3211438aefcSRuslan Ermilov 		case 'w':
3221438aefcSRuslan Ermilov 			goal_length = get_positive(optarg, "width must be positive", 1);
3231438aefcSRuslan Ermilov 			max_length = goal_length;
3241438aefcSRuslan Ermilov 			continue;
3251438aefcSRuslan Ermilov 		case '0': case '1': case '2': case '3': case '4': case '5':
3261438aefcSRuslan Ermilov 		case '6': case '7': case '8': case '9':
32786aba0f2SPedro F. Giffuni 			/*
32886aba0f2SPedro F. Giffuni 			 * XXX  this is not a stylistically approved use of
32986aba0f2SPedro F. Giffuni 			 * getopt()
33086aba0f2SPedro F. Giffuni 			 */
3311438aefcSRuslan Ermilov 			if (goal_length == 0) {
3321438aefcSRuslan Ermilov 				char *p;
33386aba0f2SPedro F. Giffuni 
3341438aefcSRuslan Ermilov 				p = argv[optind - 1];
3351438aefcSRuslan Ermilov 				if (p[0] == '-' && p[1] == ch && !p[2])
3361438aefcSRuslan Ermilov 					goal_length = get_positive(++p, "width must be nonzero", 1);
3371438aefcSRuslan Ermilov 				else
3381438aefcSRuslan Ermilov 					goal_length = get_positive(argv[optind] + 1,
3391438aefcSRuslan Ermilov 					    "width must be nonzero", 1);
3401438aefcSRuslan Ermilov 				max_length = goal_length;
3411438aefcSRuslan Ermilov 			}
3421438aefcSRuslan Ermilov 			continue;
34386aba0f2SPedro F. Giffuni 		case 'h':
34486aba0f2SPedro F. Giffuni 		default:
3451438aefcSRuslan Ermilov 			fprintf(stderr,
346d3974088SDag-Erling Smørgrav 			    "usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
3471438aefcSRuslan Ermilov 			    "             [-w width | -width | goal [maximum]] [file ...]\n"
3481438aefcSRuslan Ermilov 			    "Options: -c     center each line instead of formatting\n"
3491438aefcSRuslan Ermilov 			    "         -d <chars> double-space after <chars> at line end\n"
3501438aefcSRuslan Ermilov 			    "         -l <n> turn each <n> spaces at start of line into a tab\n"
3511438aefcSRuslan Ermilov 			    "         -m     try to make sure mail header lines stay separate\n"
352deba2451SRuslan Ermilov 			    "         -n     format lines beginning with a dot\n"
3531438aefcSRuslan Ermilov 			    "         -p     allow indented paragraphs\n"
3541438aefcSRuslan Ermilov 			    "         -s     coalesce whitespace inside lines\n"
3551438aefcSRuslan Ermilov 			    "         -t <n> have tabs every <n> columns\n"
3561438aefcSRuslan Ermilov 			    "         -w <n> set maximum width to <n>\n"
3571438aefcSRuslan Ermilov 			    "         goal   set target width to goal\n");
3581438aefcSRuslan Ermilov 			exit(ch == 'h' ? 0 : EX_USAGE);
3591438aefcSRuslan Ermilov 		}
36086aba0f2SPedro F. Giffuni 	argc -= optind;
36186aba0f2SPedro F. Giffuni 	argv += optind;
3621438aefcSRuslan Ermilov 
3631438aefcSRuslan Ermilov 	/* [ goal [ maximum ] ] */
3641438aefcSRuslan Ermilov 
3651438aefcSRuslan Ermilov 	if (argc > 0 && goal_length == 0
3661438aefcSRuslan Ermilov 	    && (goal_length = get_positive(*argv, "goal length must be positive", 0))
3671438aefcSRuslan Ermilov 	    != 0) {
36886aba0f2SPedro F. Giffuni 		--argc;
36986aba0f2SPedro F. Giffuni 		++argv;
3701438aefcSRuslan Ermilov 		if (argc > 0
3711438aefcSRuslan Ermilov 		    && (max_length = get_positive(*argv, "max length must be positive", 0))
3721438aefcSRuslan Ermilov 		    != 0) {
37386aba0f2SPedro F. Giffuni 			--argc;
37486aba0f2SPedro F. Giffuni 			++argv;
3751438aefcSRuslan Ermilov 			if (max_length < goal_length)
3761438aefcSRuslan Ermilov 				errx(EX_USAGE, "max length must be >= goal length");
3771438aefcSRuslan Ermilov 		}
3781438aefcSRuslan Ermilov 	}
37986aba0f2SPedro F. Giffuni 	if (goal_length == 0)
38086aba0f2SPedro F. Giffuni 		goal_length = 65;
38186aba0f2SPedro F. Giffuni 	if (max_length == 0)
38286aba0f2SPedro F. Giffuni 		max_length = goal_length + 10;
38386aba0f2SPedro F. Giffuni 	if (max_length >= SIZE_T_MAX / sizeof(wchar_t))
38486aba0f2SPedro F. Giffuni 		errx(EX_USAGE, "max length too large");
38528d92b74STim J. Robbins 	/* really needn't be longer */
38628d92b74STim J. Robbins 	output_buffer = XMALLOC((max_length + 1) * sizeof(wchar_t));
3871438aefcSRuslan Ermilov 
3881438aefcSRuslan Ermilov 	/* 2. Process files. */
3891438aefcSRuslan Ermilov 
3901438aefcSRuslan Ermilov 	if (argc > 0) {
39186aba0f2SPedro F. Giffuni 		while (argc-- > 0)
39286aba0f2SPedro F. Giffuni 			process_named_file(*argv++);
39386aba0f2SPedro F. Giffuni 	} else {
3941438aefcSRuslan Ermilov 		process_stream(stdin, "standard input");
3951438aefcSRuslan Ermilov 	}
3961438aefcSRuslan Ermilov 
3971438aefcSRuslan Ermilov 	/* We're done. */
3981438aefcSRuslan Ermilov 
3991438aefcSRuslan Ermilov 	return n_errors ? EX_NOINPUT : 0;
4001438aefcSRuslan Ermilov 
4011438aefcSRuslan Ermilov }
4021438aefcSRuslan Ermilov 
4031438aefcSRuslan Ermilov /* Process a single file, given its name.
4049b50d902SRodney W. Grimes  */
4051438aefcSRuslan Ermilov static void
40686aba0f2SPedro F. Giffuni process_named_file(const char *name)
40786aba0f2SPedro F. Giffuni {
4081438aefcSRuslan Ermilov 	FILE *f = fopen(name, "r");
40986aba0f2SPedro F. Giffuni 
41086aba0f2SPedro F. Giffuni 	if (!f) {
41186aba0f2SPedro F. Giffuni 		warn("%s", name);
41286aba0f2SPedro F. Giffuni 		++n_errors;
41386aba0f2SPedro F. Giffuni 	} else {
4141438aefcSRuslan Ermilov 		process_stream(f, name);
41586aba0f2SPedro F. Giffuni 		if (ferror(f)) {
41686aba0f2SPedro F. Giffuni 			warn("%s", name);
41786aba0f2SPedro F. Giffuni 			++n_errors;
41886aba0f2SPedro F. Giffuni 		}
4191438aefcSRuslan Ermilov 		fclose(f);
4209b50d902SRodney W. Grimes 	}
4219b50d902SRodney W. Grimes }
4221438aefcSRuslan Ermilov 
4231438aefcSRuslan Ermilov /* Types of mail header continuation lines:
4241438aefcSRuslan Ermilov  */
4251438aefcSRuslan Ermilov typedef enum {
4261438aefcSRuslan Ermilov 	hdr_ParagraphStart = -1,
4271438aefcSRuslan Ermilov 	hdr_NonHeader = 0,
4281438aefcSRuslan Ermilov 	hdr_Header = 1,
4291438aefcSRuslan Ermilov 	hdr_Continuation = 2
4301438aefcSRuslan Ermilov } HdrType;
4311438aefcSRuslan Ermilov 
4321438aefcSRuslan Ermilov /* Process a stream. This is where the real work happens,
4331438aefcSRuslan Ermilov  * except that centering is handled separately.
4341438aefcSRuslan Ermilov  */
4351438aefcSRuslan Ermilov static void
43686aba0f2SPedro F. Giffuni process_stream(FILE *stream, const char *name)
43786aba0f2SPedro F. Giffuni {
4381438aefcSRuslan Ermilov 	size_t last_indent = SILLY;	/* how many spaces in last indent? */
4391438aefcSRuslan Ermilov 	size_t para_line_number = 0;	/* how many lines already read in this para? */
4401438aefcSRuslan Ermilov 	size_t first_indent = SILLY;	/* indentation of line 0 of paragraph */
4411438aefcSRuslan Ermilov 	HdrType prev_header_type = hdr_ParagraphStart;
44286aba0f2SPedro F. Giffuni 
4431438aefcSRuslan Ermilov 	/* ^-- header_type of previous line; -1 at para start */
44428d92b74STim J. Robbins 	wchar_t *line;
4451438aefcSRuslan Ermilov 	size_t length;
4461438aefcSRuslan Ermilov 
44786aba0f2SPedro F. Giffuni 	if (centerP) {
44886aba0f2SPedro F. Giffuni 		center_stream(stream, name);
44986aba0f2SPedro F. Giffuni 		return;
45086aba0f2SPedro F. Giffuni 	}
4511438aefcSRuslan Ermilov 	while ((line = get_line(stream, &length)) != NULL) {
4521438aefcSRuslan Ermilov 		size_t np = indent_length(line, length);
45386aba0f2SPedro F. Giffuni 
45486aba0f2SPedro F. Giffuni 		{
45586aba0f2SPedro F. Giffuni 			HdrType header_type = hdr_NonHeader;
45686aba0f2SPedro F. Giffuni 
4571438aefcSRuslan Ermilov 			if (grok_mail_headers && prev_header_type != hdr_NonHeader) {
4581438aefcSRuslan Ermilov 				if (np == 0 && might_be_header(line))
4591438aefcSRuslan Ermilov 					header_type = hdr_Header;
4601438aefcSRuslan Ermilov 				else if (np > 0 && prev_header_type > hdr_NonHeader)
4611438aefcSRuslan Ermilov 					header_type = hdr_Continuation;
4629b50d902SRodney W. Grimes 			}
46386aba0f2SPedro F. Giffuni 			/*
46486aba0f2SPedro F. Giffuni 			 * We need a new paragraph if and only if: this line
46586aba0f2SPedro F. Giffuni 			 * is blank, OR it's a troff request (and we don't
46686aba0f2SPedro F. Giffuni 			 * format troff), OR it's a mail header, OR it's not
46786aba0f2SPedro F. Giffuni 			 * a mail header AND the last line was one, OR the
46886aba0f2SPedro F. Giffuni 			 * indentation has changed AND the line isn't a mail
46986aba0f2SPedro F. Giffuni 			 * header continuation line AND this isn't the
47086aba0f2SPedro F. Giffuni 			 * second line of an indented paragraph.
4711438aefcSRuslan Ermilov 			 */
4721438aefcSRuslan Ermilov 			if (length == 0
473deba2451SRuslan Ermilov 			    || (line[0] == '.' && !format_troff)
4741438aefcSRuslan Ermilov 			    || header_type == hdr_Header
4751438aefcSRuslan Ermilov 			    || (header_type == hdr_NonHeader && prev_header_type > hdr_NonHeader)
4761438aefcSRuslan Ermilov 			    || (np != last_indent
4771438aefcSRuslan Ermilov 			    && header_type != hdr_Continuation
4781438aefcSRuslan Ermilov 			    && (!allow_indented_paragraphs || para_line_number != 1))) {
4791438aefcSRuslan Ermilov 				new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
4801438aefcSRuslan Ermilov 				para_line_number = 0;
4811438aefcSRuslan Ermilov 				first_indent = np;
4821438aefcSRuslan Ermilov 				last_indent = np;
48386aba0f2SPedro F. Giffuni 				if (header_type == hdr_Header)
48486aba0f2SPedro F. Giffuni 					last_indent = 2;	/* for cont. lines */
485deba2451SRuslan Ermilov 				if (length == 0 || (line[0] == '.' && !format_troff)) {
486deba2451SRuslan Ermilov 					if (length == 0)
48728d92b74STim J. Robbins 						putwchar('\n');
488deba2451SRuslan Ermilov 					else
48986aba0f2SPedro F. Giffuni 						wprintf(L"%.*ls\n", (int)length,
49086aba0f2SPedro F. Giffuni 						    line);
4911438aefcSRuslan Ermilov 					prev_header_type = hdr_ParagraphStart;
4929b50d902SRodney W. Grimes 					continue;
4939b50d902SRodney W. Grimes 				}
49486aba0f2SPedro F. Giffuni 			} else {
49586aba0f2SPedro F. Giffuni 				/*
49686aba0f2SPedro F. Giffuni 				 * If this is an indented paragraph other
49786aba0f2SPedro F. Giffuni 				 * than a mail header continuation, set
49886aba0f2SPedro F. Giffuni 				 * |last_indent|.
4999b50d902SRodney W. Grimes 				 */
50086aba0f2SPedro F. Giffuni 				if (np != last_indent &&
50186aba0f2SPedro F. Giffuni 				    header_type != hdr_Continuation)
5021438aefcSRuslan Ermilov 					last_indent = np;
5031438aefcSRuslan Ermilov 			}
5041438aefcSRuslan Ermilov 			prev_header_type = header_type;
5051438aefcSRuslan Ermilov 		}
506dc3001cfSJonathan Lemon 
50786aba0f2SPedro F. Giffuni 		{
50886aba0f2SPedro F. Giffuni 			size_t n = np;
50986aba0f2SPedro F. Giffuni 
5101438aefcSRuslan Ermilov 			while (n < length) {
5111438aefcSRuslan Ermilov 				/* Find word end and count spaces after it */
5121438aefcSRuslan Ermilov 				size_t word_length = 0, space_length = 0;
51386aba0f2SPedro F. Giffuni 
51486aba0f2SPedro F. Giffuni 				while (n + word_length < length &&
51586aba0f2SPedro F. Giffuni 				    line[n + word_length] != ' ')
5161438aefcSRuslan Ermilov 					++word_length;
5171438aefcSRuslan Ermilov 				space_length = word_length;
51886aba0f2SPedro F. Giffuni 				while (n + space_length < length &&
51986aba0f2SPedro F. Giffuni 				    line[n + space_length] == ' ')
5201438aefcSRuslan Ermilov 					++space_length;
5211438aefcSRuslan Ermilov 				/* Send the word to the output machinery. */
5221438aefcSRuslan Ermilov 				output_word(first_indent, last_indent,
52386aba0f2SPedro F. Giffuni 				    line + n, word_length,
52486aba0f2SPedro F. Giffuni 				    space_length - word_length);
5251438aefcSRuslan Ermilov 				n += space_length;
5261438aefcSRuslan Ermilov 			}
5271438aefcSRuslan Ermilov 		}
5281438aefcSRuslan Ermilov 		++para_line_number;
5291438aefcSRuslan Ermilov 	}
5301438aefcSRuslan Ermilov 	new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
53186aba0f2SPedro F. Giffuni 	if (ferror(stream)) {
53286aba0f2SPedro F. Giffuni 		warn("%s", name);
53386aba0f2SPedro F. Giffuni 		++n_errors;
53486aba0f2SPedro F. Giffuni 	}
5351438aefcSRuslan Ermilov }
5369b50d902SRodney W. Grimes 
5371438aefcSRuslan Ermilov /* How long is the indent on this line?
5381438aefcSRuslan Ermilov  */
5391438aefcSRuslan Ermilov static size_t
54086aba0f2SPedro F. Giffuni indent_length(const wchar_t *line, size_t length)
54186aba0f2SPedro F. Giffuni {
5421438aefcSRuslan Ermilov 	size_t n = 0;
54386aba0f2SPedro F. Giffuni 
54486aba0f2SPedro F. Giffuni 	while (n < length && *line++ == ' ')
54586aba0f2SPedro F. Giffuni 		++n;
5461438aefcSRuslan Ermilov 	return n;
5471438aefcSRuslan Ermilov }
5481438aefcSRuslan Ermilov 
5491438aefcSRuslan Ermilov /* Might this line be a mail header?
5501438aefcSRuslan Ermilov  * We deem a line to be a possible header if it matches the
5511438aefcSRuslan Ermilov  * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
5521438aefcSRuslan Ermilov  * as in RFC whatever-number-it-is; we want to be gratuitously
5531438aefcSRuslan Ermilov  * conservative to avoid mangling ordinary civilised text.
5541438aefcSRuslan Ermilov  */
5551438aefcSRuslan Ermilov static int
55686aba0f2SPedro F. Giffuni might_be_header(const wchar_t *line)
55786aba0f2SPedro F. Giffuni {
55886aba0f2SPedro F. Giffuni 	if (!iswupper(*line++))
55986aba0f2SPedro F. Giffuni 		return 0;
56086aba0f2SPedro F. Giffuni 	while (*line && (iswalnum(*line) || *line == '-'))
56186aba0f2SPedro F. Giffuni 		++line;
56228d92b74STim J. Robbins 	return (*line == ':' && iswspace(line[1]));
5631438aefcSRuslan Ermilov }
5641438aefcSRuslan Ermilov 
5651438aefcSRuslan Ermilov /* Begin a new paragraph with an indent of |indent| spaces.
5661438aefcSRuslan Ermilov  */
5671438aefcSRuslan Ermilov static void
56886aba0f2SPedro F. Giffuni new_paragraph(size_t old_indent, size_t indent)
56986aba0f2SPedro F. Giffuni {
57028d92b74STim J. Robbins 	if (output_buffer_length) {
57186aba0f2SPedro F. Giffuni 		if (old_indent > 0)
57286aba0f2SPedro F. Giffuni 			output_indent(old_indent);
57328d92b74STim J. Robbins 		wprintf(L"%.*ls\n", (int)output_buffer_length, output_buffer);
5743f8da92bSPoul-Henning Kamp 	}
57586aba0f2SPedro F. Giffuni 	x = indent;
57686aba0f2SPedro F. Giffuni 	x0 = 0;
57786aba0f2SPedro F. Giffuni 	output_buffer_length = 0;
57886aba0f2SPedro F. Giffuni 	pending_spaces = 0;
5791438aefcSRuslan Ermilov 	output_in_paragraph = 0;
5809b50d902SRodney W. Grimes }
5819b50d902SRodney W. Grimes 
5821438aefcSRuslan Ermilov /* Output spaces or tabs for leading indentation.
5839b50d902SRodney W. Grimes  */
5841438aefcSRuslan Ermilov static void
58586aba0f2SPedro F. Giffuni output_indent(size_t n_spaces)
58686aba0f2SPedro F. Giffuni {
5871438aefcSRuslan Ermilov 	if (output_tab_width) {
5881438aefcSRuslan Ermilov 		while (n_spaces >= output_tab_width) {
58928d92b74STim J. Robbins 			putwchar('\t');
5901438aefcSRuslan Ermilov 			n_spaces -= output_tab_width;
5911438aefcSRuslan Ermilov 		}
5921438aefcSRuslan Ermilov 	}
59386aba0f2SPedro F. Giffuni 	while (n_spaces-- > 0)
59486aba0f2SPedro F. Giffuni 		putwchar(' ');
5951438aefcSRuslan Ermilov }
5969b50d902SRodney W. Grimes 
5971438aefcSRuslan Ermilov /* Output a single word, or add it to the buffer.
5981438aefcSRuslan Ermilov  * indent0 and indent1 are the indents to use on the first and subsequent
5991438aefcSRuslan Ermilov  * lines of a paragraph. They'll often be the same, of course.
6001438aefcSRuslan Ermilov  */
6011438aefcSRuslan Ermilov static void
60286aba0f2SPedro F. Giffuni output_word(size_t indent0, size_t indent1, const wchar_t *word, size_t length, size_t spaces)
60386aba0f2SPedro F. Giffuni {
60428d92b74STim J. Robbins 	size_t new_x;
6051438aefcSRuslan Ermilov 	size_t indent = output_in_paragraph ? indent1 : indent0;
60628d92b74STim J. Robbins 	size_t width;
60728d92b74STim J. Robbins 	const wchar_t *p;
60828d92b74STim J. Robbins 	int cwidth;
60928d92b74STim J. Robbins 
61028d92b74STim J. Robbins 	for (p = word, width = 0; p < &word[length]; p++)
61128d92b74STim J. Robbins 		width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1;
61228d92b74STim J. Robbins 
61328d92b74STim J. Robbins 	new_x = x + pending_spaces + width;
6141438aefcSRuslan Ermilov 
61586aba0f2SPedro F. Giffuni 	/*
61686aba0f2SPedro F. Giffuni 	 * If either |spaces==0| (at end of line) or |coalesce_spaces_P|
61786aba0f2SPedro F. Giffuni 	 * (squashing internal whitespace), then add just one space; except
61886aba0f2SPedro F. Giffuni 	 * that if the last character was a sentence-ender we actually add
61986aba0f2SPedro F. Giffuni 	 * two spaces.
6201438aefcSRuslan Ermilov 	 */
6211438aefcSRuslan Ermilov 	if (coalesce_spaces_P || spaces == 0)
62228d92b74STim J. Robbins 		spaces = wcschr(sentence_enders, word[length - 1]) ? 2 : 1;
6231438aefcSRuslan Ermilov 
6241438aefcSRuslan Ermilov 	if (new_x <= goal_length) {
62586aba0f2SPedro F. Giffuni 		/*
62686aba0f2SPedro F. Giffuni 		 * After adding the word we still aren't at the goal length,
62786aba0f2SPedro F. Giffuni 		 * so clearly we add it to the buffer rather than outputing
62886aba0f2SPedro F. Giffuni 		 * it.
6291438aefcSRuslan Ermilov 		 */
63086aba0f2SPedro F. Giffuni 		wmemset(output_buffer + output_buffer_length, L' ',
63186aba0f2SPedro F. Giffuni 		    pending_spaces);
63286aba0f2SPedro F. Giffuni 		x0 += pending_spaces;
63386aba0f2SPedro F. Giffuni 		x += pending_spaces;
63428d92b74STim J. Robbins 		output_buffer_length += pending_spaces;
63528d92b74STim J. Robbins 		wmemcpy(output_buffer + output_buffer_length, word, length);
63686aba0f2SPedro F. Giffuni 		x0 += width;
63786aba0f2SPedro F. Giffuni 		x += width;
63886aba0f2SPedro F. Giffuni 		output_buffer_length += length;
6391438aefcSRuslan Ermilov 		pending_spaces = spaces;
64086aba0f2SPedro F. Giffuni 	} else {
64186aba0f2SPedro F. Giffuni 		/*
64286aba0f2SPedro F. Giffuni 		 * Adding the word takes us past the goal. Print the
64386aba0f2SPedro F. Giffuni 		 * line-so-far, and the word too iff either (1) the lsf is
64486aba0f2SPedro F. Giffuni 		 * empty or (2) that makes us nearer the goal but doesn't
64586aba0f2SPedro F. Giffuni 		 * take us over the limit, or (3) the word on its own takes
64686aba0f2SPedro F. Giffuni 		 * us over the limit. In case (3) we put a newline in
64786aba0f2SPedro F. Giffuni 		 * between.
6481438aefcSRuslan Ermilov 		 */
64986aba0f2SPedro F. Giffuni 		if (indent > 0)
65086aba0f2SPedro F. Giffuni 			output_indent(indent);
65128d92b74STim J. Robbins 		wprintf(L"%.*ls", (int)output_buffer_length, output_buffer);
65286aba0f2SPedro F. Giffuni 		if (x0 == 0 || (new_x <= max_length &&
65386aba0f2SPedro F. Giffuni 		    new_x - goal_length <= goal_length - x)) {
65428d92b74STim J. Robbins 			wprintf(L"%*ls", (int)pending_spaces, L"");
6551438aefcSRuslan Ermilov 			goto write_out_word;
65686aba0f2SPedro F. Giffuni 		} else {
65786aba0f2SPedro F. Giffuni 			/*
65886aba0f2SPedro F. Giffuni 			 * If the word takes us over the limit on its own,
65986aba0f2SPedro F. Giffuni 			 * just spit it out and don't bother buffering it.
6601438aefcSRuslan Ermilov 			 */
66128d92b74STim J. Robbins 			if (indent + width > max_length) {
66228d92b74STim J. Robbins 				putwchar('\n');
66386aba0f2SPedro F. Giffuni 				if (indent > 0)
66486aba0f2SPedro F. Giffuni 					output_indent(indent);
6651438aefcSRuslan Ermilov 		write_out_word:
66628d92b74STim J. Robbins 				wprintf(L"%.*ls", (int)length, word);
66786aba0f2SPedro F. Giffuni 				x0 = 0;
66886aba0f2SPedro F. Giffuni 				x = indent1;
66986aba0f2SPedro F. Giffuni 				pending_spaces = 0;
67028d92b74STim J. Robbins 				output_buffer_length = 0;
67186aba0f2SPedro F. Giffuni 			} else {
67228d92b74STim J. Robbins 				wmemcpy(output_buffer, word, length);
67386aba0f2SPedro F. Giffuni 				x0 = width;
67486aba0f2SPedro F. Giffuni 				x = width + indent1;
67586aba0f2SPedro F. Giffuni 				pending_spaces = spaces;
67628d92b74STim J. Robbins 				output_buffer_length = length;
6779b50d902SRodney W. Grimes 			}
6789b50d902SRodney W. Grimes 		}
67928d92b74STim J. Robbins 		putwchar('\n');
6801438aefcSRuslan Ermilov 		output_in_paragraph = 1;
6819c61e111SJoerg Wunsch 	}
6829c61e111SJoerg Wunsch }
6839c61e111SJoerg Wunsch 
6841438aefcSRuslan Ermilov /* Process a stream, but just center its lines rather than trying to
6851438aefcSRuslan Ermilov  * format them neatly.
6869b50d902SRodney W. Grimes  */
6871438aefcSRuslan Ermilov static void
68886aba0f2SPedro F. Giffuni center_stream(FILE *stream, const char *name)
68986aba0f2SPedro F. Giffuni {
69028d92b74STim J. Robbins 	wchar_t *line, *p;
6911438aefcSRuslan Ermilov 	size_t length;
69228d92b74STim J. Robbins 	size_t width;
69328d92b74STim J. Robbins 	int cwidth;
69486aba0f2SPedro F. Giffuni 
695*074e77e6SPedro F. Giffuni 	while ((line = get_line(stream, &length)) != NULL) {
6961438aefcSRuslan Ermilov 		size_t l = length;
69786aba0f2SPedro F. Giffuni 
69886aba0f2SPedro F. Giffuni 		while (l > 0 && iswspace(*line)) {
69986aba0f2SPedro F. Giffuni 			++line;
70086aba0f2SPedro F. Giffuni 			--l;
70186aba0f2SPedro F. Giffuni 		}
7021438aefcSRuslan Ermilov 		length = l;
70328d92b74STim J. Robbins 		for (p = line, width = 0; p < &line[length]; p++)
70428d92b74STim J. Robbins 			width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1;
70528d92b74STim J. Robbins 		l = width;
70686aba0f2SPedro F. Giffuni 		while (l < goal_length) {
70786aba0f2SPedro F. Giffuni 			putwchar(' ');
70886aba0f2SPedro F. Giffuni 			l += 2;
70986aba0f2SPedro F. Giffuni 		}
71028d92b74STim J. Robbins 		wprintf(L"%.*ls\n", (int)length, line);
7111438aefcSRuslan Ermilov 	}
71286aba0f2SPedro F. Giffuni 	if (ferror(stream)) {
71386aba0f2SPedro F. Giffuni 		warn("%s", name);
71486aba0f2SPedro F. Giffuni 		++n_errors;
71586aba0f2SPedro F. Giffuni 	}
7169b50d902SRodney W. Grimes }
7179b50d902SRodney W. Grimes 
7181438aefcSRuslan Ermilov /* Get a single line from a stream. Expand tabs, strip control
7191438aefcSRuslan Ermilov  * characters and trailing whitespace, and handle backspaces.
7201438aefcSRuslan Ermilov  * Return the address of the buffer containing the line, and
7211438aefcSRuslan Ermilov  * put the length of the line in |lengthp|.
7221438aefcSRuslan Ermilov  * This can cope with arbitrarily long lines, and with lines
7231438aefcSRuslan Ermilov  * without terminating \n.
7241438aefcSRuslan Ermilov  * If there are no characters left or an error happens, we
7251438aefcSRuslan Ermilov  * return 0.
7261438aefcSRuslan Ermilov  * Don't confuse |spaces_pending| here with the global
7271438aefcSRuslan Ermilov  * |pending_spaces|.
7289b50d902SRodney W. Grimes  */
72928d92b74STim J. Robbins static wchar_t *
73086aba0f2SPedro F. Giffuni get_line(FILE *stream, size_t *lengthp)
73186aba0f2SPedro F. Giffuni {
73228d92b74STim J. Robbins 	static wchar_t *buf = NULL;
7331438aefcSRuslan Ermilov 	static size_t length = 0;
7341438aefcSRuslan Ermilov 	size_t len = 0;
73528d92b74STim J. Robbins 	wint_t ch;
7361438aefcSRuslan Ermilov 	size_t spaces_pending = 0;
737deba2451SRuslan Ermilov 	int troff = 0;
73828d92b74STim J. Robbins 	size_t col = 0;
73928d92b74STim J. Robbins 	int cwidth;
7401438aefcSRuslan Ermilov 
74186aba0f2SPedro F. Giffuni 	if (buf == NULL) {
74286aba0f2SPedro F. Giffuni 		length = 100;
74386aba0f2SPedro F. Giffuni 		buf = XMALLOC(length * sizeof(wchar_t));
74486aba0f2SPedro F. Giffuni 	}
74528d92b74STim J. Robbins 	while ((ch = getwc(stream)) != '\n' && ch != WEOF) {
74686aba0f2SPedro F. Giffuni 		if (len + spaces_pending == 0 && ch == '.' && !format_troff)
74786aba0f2SPedro F. Giffuni 			troff = 1;
74886aba0f2SPedro F. Giffuni 		if (ch == ' ')
74986aba0f2SPedro F. Giffuni 			++spaces_pending;
75028d92b74STim J. Robbins 		else if (troff || iswprint(ch)) {
7511438aefcSRuslan Ermilov 			while (len + spaces_pending >= length) {
75286aba0f2SPedro F. Giffuni 				length *= 2;
75386aba0f2SPedro F. Giffuni 				buf = xrealloc(buf, length * sizeof(wchar_t));
7549b50d902SRodney W. Grimes 			}
75586aba0f2SPedro F. Giffuni 			while (spaces_pending > 0) {
75686aba0f2SPedro F. Giffuni 				--spaces_pending;
75786aba0f2SPedro F. Giffuni 				buf[len++] = ' ';
75886aba0f2SPedro F. Giffuni 				col++;
75986aba0f2SPedro F. Giffuni 			}
7601438aefcSRuslan Ermilov 			buf[len++] = ch;
76128d92b74STim J. Robbins 			col += (cwidth = wcwidth(ch)) > 0 ? cwidth : 1;
76286aba0f2SPedro F. Giffuni 		} else if (ch == '\t')
76386aba0f2SPedro F. Giffuni 			spaces_pending += tab_width -
76486aba0f2SPedro F. Giffuni 			    (col + spaces_pending) % tab_width;
76586aba0f2SPedro F. Giffuni 		else if (ch == '\b') {
76686aba0f2SPedro F. Giffuni 			if (len)
76786aba0f2SPedro F. Giffuni 				--len;
76886aba0f2SPedro F. Giffuni 			if (col)
76986aba0f2SPedro F. Giffuni 				--col;
7709b50d902SRodney W. Grimes 		}
7711438aefcSRuslan Ermilov 	}
7721438aefcSRuslan Ermilov 	*lengthp = len;
77328d92b74STim J. Robbins 	return (len > 0 || ch != WEOF) ? buf : 0;
7749b50d902SRodney W. Grimes }
7759b50d902SRodney W. Grimes 
7761438aefcSRuslan Ermilov /* (Re)allocate some memory, exiting with an error if we can't.
7779b50d902SRodney W. Grimes  */
7781438aefcSRuslan Ermilov static void *
77986aba0f2SPedro F. Giffuni xrealloc(void *ptr, size_t nbytes)
78086aba0f2SPedro F. Giffuni {
7811438aefcSRuslan Ermilov 	void *p = realloc(ptr, nbytes);
78286aba0f2SPedro F. Giffuni 
78386aba0f2SPedro F. Giffuni 	if (p == NULL)
78486aba0f2SPedro F. Giffuni 		errx(EX_OSERR, "out of memory");
7851438aefcSRuslan Ermilov 	return p;
7869b50d902SRodney W. Grimes }
787