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