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