fmt.c revision 95258
177807Sru/*	$OpenBSD: fmt.c,v 1.16 2000/06/25 15:35:42 pjanzen Exp $	*/
277807Sru
377807Sru/* Sensible version of fmt
41590Srgrimes *
577807Sru * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ]
677807Sru *
777807Sru * Since the documentation for the original fmt is so poor, here
877807Sru * is an accurate description of what this one does. It's usually
977807Sru * the same. The *mechanism* used may differ from that suggested
1077807Sru * here. Note that we are *not* entirely compatible with fmt,
1177807Sru * because fmt gets so many things wrong.
1277807Sru *
1377807Sru * 1. Tabs are expanded, assuming 8-space tab stops.
1477807Sru *    If the `-t <n>' option is given, we assume <n>-space
1577807Sru *    tab stops instead.
1677807Sru *    Trailing blanks are removed from all lines.
1777807Sru *    x\b == nothing, for any x other than \b.
1877807Sru *    Other control characters are simply stripped. This
1977807Sru *    includes \r.
2077807Sru * 2. Each line is split into leading whitespace and
2177807Sru *    everything else. Maximal consecutive sequences of
2277807Sru *    lines with the same leading whitespace are considered
2377807Sru *    to form paragraphs, except that a blank line is always
2477807Sru *    a paragraph to itself.
2577807Sru *    If the `-p' option is given then the first line of a
2677807Sru *    paragraph is permitted to have indentation different
2777807Sru *    from that of the other lines.
2877807Sru *    If the `-m' option is given then a line that looks
2977807Sru *    like a mail message header, if it is not immediately
3077807Sru *    preceded by a non-blank non-message-header line, is
3177807Sru *    taken to start a new paragraph, which also contains
3277807Sru *    any subsequent lines with non-empty leading whitespace.
3389268Sru *    Unless the `-n' option is given, lines beginning with
3489268Sru *    a . (dot) are not formatted.
3577807Sru * 3. The "everything else" is split into words; a word
3677807Sru *    includes its trailing whitespace, and a word at the
3777807Sru *    end of a line is deemed to be followed by a single
3877807Sru *    space, or two spaces if it ends with a sentence-end
3977807Sru *    character. (See the `-d' option for how to change that.)
4077807Sru *    If the `-s' option has been given, then a word's trailing
4177807Sru *    whitespace is replaced by what it would have had if it
4277807Sru *    had occurred at end of line.
4377807Sru * 4. Each paragraph is sent to standard output as follows.
4477807Sru *    We output the leading whitespace, and then enough words
4577807Sru *    to make the line length as near as possible to the goal
4677807Sru *    without exceeding the maximum. (If a single word would
4777807Sru *    exceed the maximum, we output that anyway.) Of course
4877807Sru *    the trailing whitespace of the last word is ignored.
4977807Sru *    We then emit a newline and start again if there are any
5077807Sru *    words left.
5177807Sru *    Note that for a blank line this translates as "We emit
5277807Sru *    a newline".
5377807Sru *    If the `-l <n>' option is given, then leading whitespace
5477807Sru *    is modified slightly: <n> spaces are replaced by a tab.
5577807Sru *    Indented paragraphs (see above under `-p') make matters
5677807Sru *    more complicated than this suggests. Actually every paragraph
5777807Sru *    has two `leading whitespace' values; the value for the first
5877807Sru *    line, and the value for the most recent line. (While processing
5977807Sru *    the first line, the two are equal. When `-p' has not been
6077807Sru *    given, they are always equal.) The leading whitespace
6177807Sru *    actually output is that of the first line (for the first
6277807Sru *    line of *output*) or that of the most recent line (for
6377807Sru *    all other lines of output).
6477807Sru *    When `-m' has been given, message header paragraphs are
6577807Sru *    taken as having first-leading-whitespace empty and
6677807Sru *    subsequent-leading-whitespace two spaces.
6777807Sru *
6877807Sru * Multiple input files are formatted one at a time, so that a file
6977807Sru * never ends in the middle of a line.
7077807Sru *
7177807Sru * There's an alternative mode of operation, invoked by giving
7277807Sru * the `-c' option. In that case we just center every line,
7377807Sru * and most of the other options are ignored. This should
7477807Sru * really be in a separate program, but we must stay compatible
7577807Sru * with old `fmt'.
7677807Sru *
7777807Sru * QUERY: Should `-m' also try to do the right thing with quoted text?
7877807Sru * QUERY: `-b' to treat backslashed whitespace as old `fmt' does?
7977807Sru * QUERY: Option meaning `never join lines'?
8077807Sru * QUERY: Option meaning `split in mid-word to avoid overlong lines'?
8177807Sru * (Those last two might not be useful, since we have `fold'.)
8277807Sru *
8377807Sru * Differences from old `fmt':
8477807Sru *
8577807Sru *   - We have many more options. Options that aren't understood
8677807Sru *     generate a lengthy usage message, rather than being
8777807Sru *     treated as filenames.
8877807Sru *   - Even with `-m', our handling of message headers is
8977807Sru *     significantly different. (And much better.)
9077807Sru *   - We don't treat `\ ' as non-word-breaking.
9177807Sru *   - Downward changes of indentation start new paragraphs
9277807Sru *     for us, as well as upward. (I think old `fmt' behaves
9377807Sru *     in the way it does in order to allow indented paragraphs,
9477807Sru *     but this is a broken way of making indented paragraphs
9577807Sru *     behave right.)
9677807Sru *   - Given the choice of going over or under |goal_length|
9777807Sru *     by the same amount, we go over; old `fmt' goes under.
9877807Sru *   - We treat `?' as ending a sentence, and not `:'. Old `fmt'
9977807Sru *     does the reverse.
10077807Sru *   - We return approved return codes. Old `fmt' returns
10177807Sru *     1 for some errors, and *the number of unopenable files*
10277807Sru *     when that was all that went wrong.
10377807Sru *   - We have fewer crashes and more helpful error messages.
10477807Sru *   - We don't turn spaces into tabs at starts of lines unless
10577807Sru *     specifically requested.
10677807Sru *   - New `fmt' is somewhat smaller and slightly faster than
10777807Sru *     old `fmt'.
10877807Sru *
10977807Sru * Bugs:
11077807Sru *
11177807Sru *   None known. There probably are some, though.
11277807Sru *
11377807Sru * Portability:
11477807Sru *
11577807Sru *   I believe this code to be pretty portable. It does require
11677807Sru *   that you have `getopt'. If you need to include "getopt.h"
11777807Sru *   for this (e.g., if your system didn't come with `getopt'
11877807Sru *   and you installed it yourself) then you should arrange for
11977807Sru *   NEED_getopt_h to be #defined.
12077807Sru *
12177807Sru *   Everything here should work OK even on nasty 16-bit
12277807Sru *   machines and nice 64-bit ones. However, it's only really
12377807Sru *   been tested on my FreeBSD machine. Your mileage may vary.
12477807Sru */
12577807Sru
12677807Sru/* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
12777807Sru *
12877807Sru * Redistribution and use of this code, in source or binary forms,
12977807Sru * with or without modification, are permitted subject to the following
13077807Sru * conditions:
13177807Sru *
13277807Sru *  - Redistribution of source code must retain the above copyright
1331590Srgrimes *    notice, this list of conditions and the following disclaimer.
1341590Srgrimes *
13577807Sru *  - If you distribute modified source code it must also include
13677807Sru *    a notice saying that it has been modified, and giving a brief
13777807Sru *    description of what changes have been made.
13877807Sru *
13977807Sru * Disclaimer: I am not responsible for the results of using this code.
14077807Sru *             If it formats your hard disc, sends obscene messages to
14177807Sru *             your boss and kills your children then that's your problem
14277807Sru *             not mine. I give absolutely no warranty of any sort as to
14377807Sru *             what the program will do, and absolutely refuse to be held
14477807Sru *             liable for any consequences of your using it.
14577807Sru *             Thank you. Have a nice day.
1461590Srgrimes */
1471590Srgrimes
14877807Sru/* RCS change log:
14977807Sru * Revision 1.5  1998/03/02 18:02:21  gjm11
15077807Sru * Minor changes for portability.
15177807Sru *
15277807Sru * Revision 1.4  1997/10/01 11:51:28  gjm11
15377807Sru * Repair broken indented-paragraph handling.
15477807Sru * Add mail message header stuff.
15577807Sru * Improve comments and layout.
15677807Sru * Make usable with non-BSD systems.
15777807Sru * Add revision display to usage message.
15877807Sru *
15977807Sru * Revision 1.3  1997/09/30 16:24:47  gjm11
16077807Sru * Add copyright notice, rcsid string and log message.
16177807Sru *
16277807Sru * Revision 1.2  1997/09/30 16:13:39  gjm11
16377807Sru * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h .
16477807Sru * Parse options with `getopt'. Clean up code generally.
16577807Sru * Make comments more accurate.
16677807Sru *
16777807Sru * Revision 1.1  1997/09/30 11:29:57  gjm11
16877807Sru * Initial revision
16977807Sru */
1701590Srgrimes
1711590Srgrimes#ifndef lint
17227185Scharnierstatic const char rcsid[] =
17350477Speter  "$FreeBSD: head/usr.bin/fmt/fmt.c 95258 2002-04-22 13:44:47Z des $";
17477807Srustatic const char copyright[] =
17577807Sru  "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n";
1761590Srgrimes#endif /* not lint */
1771590Srgrimes
1781590Srgrimes#include <ctype.h>
17927185Scharnier#include <err.h>
18011765Sache#include <locale.h>
18127185Scharnier#include <stdio.h>
18212317Sjoerg#include <stdlib.h>
18327185Scharnier#include <string.h>
18477807Sru#include <sysexits.h>
18577807Sru#include <unistd.h>
1861590Srgrimes
18777807Sru/* Something that, we hope, will never be a genuine line length,
18877807Sru * indentation etc.
1891590Srgrimes */
19077807Sru#define SILLY ((size_t)-1)
1911590Srgrimes
19277807Sru/* I used to use |strtoul| for this, but (1) not all systems have it
19377807Sru * and (2) it's probably better to use |strtol| to detect negative
19477807Sru * numbers better.
19577807Sru * If |fussyp==0| then we don't complain about non-numbers
19677807Sru * (returning 0 instead), but we do complain about bad numbers.
1971590Srgrimes */
19877807Srustatic size_t
19977807Sruget_positive(const char *s, const char *err_mess, int fussyP) {
20077807Sru  char *t;
20177807Sru  long result = strtol(s,&t,0);
20277807Sru  if (*t) { if (fussyP) goto Lose; else return 0; }
20381510Skris  if (result<=0) { Lose: errx(EX_USAGE, "%s", err_mess); }
20477807Sru  return (size_t) result;
20577807Sru}
2061590Srgrimes
20781701Srustatic size_t
20881701Sruget_nonnegative(const char *s, const char *err_mess, int fussyP) {
20981701Sru  char *t;
21081701Sru  long result = strtol(s,&t,0);
21181701Sru  if (*t) { if (fussyP) goto Lose; else return 0; }
21281701Sru  if (result<0) { Lose: errx(EX_USAGE, "%s", err_mess); }
21381701Sru  return (size_t) result;
21481701Sru}
21581701Sru
21677807Sru/* Global variables */
2171590Srgrimes
21877807Srustatic int centerP=0;		/* Try to center lines? */
21977807Srustatic size_t goal_length=0;	/* Target length for output lines */
22077807Srustatic size_t max_length=0;	/* Maximum length for output lines */
22177807Srustatic int coalesce_spaces_P=0;	/* Coalesce multiple whitespace -> ' ' ? */
22277807Srustatic int allow_indented_paragraphs=0;	/* Can first line have diff. ind.? */
22377807Srustatic int tab_width=8;		/* Number of spaces per tab stop */
22481701Srustatic size_t output_tab_width=8;	/* Ditto, when squashing leading spaces */
22577807Srustatic const char *sentence_enders=".?!";	/* Double-space after these */
22677807Srustatic int grok_mail_headers=0;	/* treat embedded mail headers magically? */
22789268Srustatic int format_troff=0;	/* Format troff? */
2281590Srgrimes
22977807Srustatic int n_errors=0;		/* Number of failed files. Return on exit. */
23077807Srustatic char *output_buffer=0;	/* Output line will be built here */
23177807Srustatic size_t x;		/* Horizontal position in output line */
23277807Srustatic size_t x0;		/* Ditto, ignoring leading whitespace */
23377807Srustatic size_t pending_spaces;	/* Spaces to add before next word */
23477807Srustatic int output_in_paragraph=0;	/* Any of current para written out yet? */
23527185Scharnier
23677807Sru/* Prototypes */
23777807Sru
23877807Srustatic void process_named_file (const char *);
23977807Srustatic void     process_stream (FILE *, const char *);
24077807Srustatic size_t    indent_length (const char *, size_t);
24177807Srustatic int     might_be_header (const unsigned char *);
24277807Srustatic void      new_paragraph (size_t, size_t);
24377807Srustatic void        output_word (size_t, size_t, const char *, size_t, size_t);
24477807Srustatic void      output_indent (size_t);
24577807Srustatic void      center_stream (FILE *, const char *);
24677807Srustatic char *         get_line (FILE *, size_t *);
24777807Srustatic void *         xrealloc (void *, size_t);
24877807Sru
24977807Sru#define XMALLOC(x) xrealloc(0,x)
25077807Sru
25177807Sru/* Here is perhaps the right place to mention that this code is
25277807Sru * all in top-down order. Hence, |main| comes first.
2531590Srgrimes */
25427185Scharnierint
25577807Srumain(int argc, char *argv[]) {
25677807Sru  int ch;			/* used for |getopt| processing */
2571590Srgrimes
25811765Sache
25977807Sru  (void) setlocale(LC_CTYPE, "");
2601590Srgrimes
26177807Sru  /* 1. Grok parameters. */
2621590Srgrimes
26389268Sru  while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1)
26477807Sru  switch(ch) {
26577807Sru    case 'c':
26677807Sru      centerP = 1;
26789268Sru      format_troff = 1;
26877807Sru      continue;
26977807Sru    case 'd':
27077807Sru      sentence_enders = optarg;
27177807Sru      continue;
27277807Sru    case 'l':
27377807Sru      output_tab_width
27481701Sru        = get_nonnegative(optarg, "output tab width must be non-negative", 1);
27577807Sru      continue;
27677807Sru    case 'm':
27777807Sru      grok_mail_headers = 1;
27877807Sru      continue;
27989268Sru    case 'n':
28089268Sru      format_troff = 1;
28189268Sru      continue;
28277807Sru    case 'p':
28377807Sru      allow_indented_paragraphs = 1;
28477807Sru      continue;
28577807Sru    case 's':
28677807Sru      coalesce_spaces_P = 1;
28777807Sru      continue;
28877807Sru    case 't':
28977807Sru      tab_width = get_positive(optarg, "tab width must be positive", 1);
29077807Sru      continue;
29177807Sru    case 'w':
29277807Sru      goal_length = get_positive(optarg, "width must be positive", 1);
29377807Sru      max_length = goal_length;
29477807Sru      continue;
29577807Sru    case '0': case '1': case '2': case '3': case '4': case '5':
29677807Sru    case '6': case '7': case '8': case '9':
29777807Sru    /* XXX  this is not a stylistically approved use of getopt() */
29877807Sru      if (goal_length==0) {
29977807Sru        char *p;
30077807Sru        p = argv[optind - 1];
30177807Sru        if (p[0] == '-' && p[1] == ch && !p[2])
30277807Sru             goal_length = get_positive(++p, "width must be nonzero", 1);
30377807Sru        else
30477807Sru             goal_length = get_positive(argv[optind]+1,
30577807Sru                 "width must be nonzero", 1);
30677807Sru        max_length = goal_length;
30777807Sru      }
30877807Sru      continue;
30977807Sru    case 'h': default:
31077807Sru      fprintf(stderr,
31195258Sdes"usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
31277807Sru"             [-w width | -width | goal [maximum]] [file ...]\n"
31377807Sru"Options: -c     center each line instead of formatting\n"
31477807Sru"         -d <chars> double-space after <chars> at line end\n"
31577807Sru"         -l <n> turn each <n> spaces at start of line into a tab\n"
31677807Sru"         -m     try to make sure mail header lines stay separate\n"
31789268Sru"         -n     format lines beginning with a dot\n"
31877807Sru"         -p     allow indented paragraphs\n"
31977807Sru"         -s     coalesce whitespace inside lines\n"
32077807Sru"         -t <n> have tabs every <n> columns\n"
32177807Sru"         -w <n> set maximum width to <n>\n"
32277807Sru"         goal   set target width to goal\n");
32377807Sru      exit(ch=='h' ? 0 : EX_USAGE);
32477807Sru  }
32577807Sru  argc -= optind; argv += optind;
32628478Sjlemon
32777807Sru  /* [ goal [ maximum ] ] */
3281590Srgrimes
32977807Sru  if (argc>0 && goal_length==0
33077807Sru      && (goal_length=get_positive(*argv,"goal length must be positive", 0))
33177807Sru         != 0) {
33277807Sru    --argc; ++argv;
33377807Sru    if (argc>0
33477807Sru        && (max_length=get_positive(*argv,"max length must be positive", 0))
33577807Sru           != 0) {
33677807Sru      --argc; ++argv;
33777807Sru      if (max_length<goal_length)
33877807Sru        errx(EX_USAGE, "max length must be >= goal length");
33977807Sru    }
34077807Sru  }
34177807Sru  if (goal_length==0) goal_length = 65;
34277807Sru  if (max_length==0) max_length = goal_length+10;
34377807Sru  output_buffer = XMALLOC(max_length+1);	/* really needn't be longer */
3448874Srgrimes
34577807Sru  /* 2. Process files. */
34615344Ssmpatel
34777807Sru  if (argc>0) {
34877807Sru    while (argc-->0) process_named_file(*argv++);
34977807Sru  }
35077807Sru  else {
35177807Sru    process_stream(stdin, "standard input");
35277807Sru  }
3531590Srgrimes
35477807Sru  /* We're done. */
35577807Sru
35677807Sru  return n_errors ? EX_NOINPUT : 0;
35777807Sru
3581590Srgrimes}
3591590Srgrimes
36077807Sru/* Process a single file, given its name.
3611590Srgrimes */
36277807Srustatic void
36377807Sruprocess_named_file(const char *name) {
36477807Sru  FILE *f=fopen(name, "r");
36577807Sru  if (!f) { perror(name); ++n_errors; }
36677807Sru  else {
36777807Sru    process_stream(f, name);
36877807Sru    fclose(f);
36977807Sru  }
3701590Srgrimes}
3711590Srgrimes
37277807Sru/* Types of mail header continuation lines:
3731590Srgrimes */
37477807Srutypedef enum {
37577807Sru  hdr_ParagraphStart = -1,
37677807Sru  hdr_NonHeader      = 0,
37777807Sru  hdr_Header         = 1,
37877807Sru  hdr_Continuation   = 2
37977807Sru} HdrType;
3801590Srgrimes
38177807Sru/* Process a stream. This is where the real work happens,
38277807Sru * except that centering is handled separately.
38377807Sru */
38477807Srustatic void
38577807Sruprocess_stream(FILE *stream, const char *name) {
38677807Sru  size_t last_indent=SILLY;	/* how many spaces in last indent? */
38777807Sru  size_t para_line_number=0;	/* how many lines already read in this para? */
38877807Sru  size_t first_indent=SILLY;	/* indentation of line 0 of paragraph */
38977807Sru  HdrType prev_header_type=hdr_ParagraphStart;
39077807Sru	/* ^-- header_type of previous line; -1 at para start */
39177807Sru  char *line;
39277807Sru  size_t length;
39330009Sjoerg
39477807Sru  if (centerP) { center_stream(stream, name); return; }
39577807Sru  while ((line=get_line(stream,&length)) != NULL) {
39677807Sru    size_t np=indent_length(line, length);
39777807Sru    { HdrType header_type=hdr_NonHeader;
39877807Sru      if (grok_mail_headers && prev_header_type!=hdr_NonHeader) {
39977807Sru        if (np==0 && might_be_header(line))
40077807Sru          header_type = hdr_Header;
40177807Sru        else if (np>0 && prev_header_type>hdr_NonHeader)
40277807Sru          header_type = hdr_Continuation;
40377807Sru      }
40477807Sru      /* We need a new paragraph if and only if:
40577807Sru       *   this line is blank,
40689268Sru       *   OR it's a troff request (and we don't format troff),
40777807Sru       *   OR it's a mail header,
40877807Sru       *   OR it's not a mail header AND the last line was one,
40977807Sru       *   OR the indentation has changed
41077807Sru       *      AND the line isn't a mail header continuation line
41177807Sru       *      AND this isn't the second line of an indented paragraph.
41277807Sru       */
41377807Sru      if ( length==0
41489268Sru           || (line[0]=='.' && !format_troff)
41577807Sru           || header_type==hdr_Header
41677807Sru           || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader)
41777807Sru           || (np!=last_indent
41877807Sru               && header_type != hdr_Continuation
41977807Sru               && (!allow_indented_paragraphs || para_line_number != 1)) ) {
42077807Sru        new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
42177807Sru        para_line_number = 0;
42277807Sru        first_indent = np;
42377807Sru        last_indent = np;
42477807Sru        if (header_type==hdr_Header) last_indent=2;	/* for cont. lines */
42589268Sru        if (length==0 || (line[0]=='.' && !format_troff)) {
42689268Sru          if (length==0)
42789268Sru            putchar('\n');
42889268Sru          else
42989268Sru            printf("%.*s\n", (int)length, line);
43077807Sru          prev_header_type=hdr_ParagraphStart;
43177807Sru          continue;
43277807Sru        }
43377807Sru      }
43477807Sru      else {
43577807Sru        /* If this is an indented paragraph other than a mail header
43677807Sru         * continuation, set |last_indent|.
43777807Sru         */
43877807Sru        if (np != last_indent && header_type != hdr_Continuation)
43977807Sru          last_indent=np;
44077807Sru      }
44177807Sru      prev_header_type = header_type;
44277807Sru    }
4431590Srgrimes
44477807Sru    { size_t n=np;
44577807Sru      while (n<length) {
44677807Sru        /* Find word end and count spaces after it */
44777807Sru        size_t word_length=0, space_length=0;
44877807Sru        while (n+word_length < length && line[n+word_length] != ' ')
44977807Sru          ++word_length;
45077807Sru        space_length = word_length;
45177807Sru        while (n+space_length < length && line[n+space_length] == ' ')
45277807Sru          ++space_length;
45377807Sru        /* Send the word to the output machinery. */
45477807Sru        output_word(first_indent, last_indent,
45577807Sru                    line+n, word_length, space_length-word_length);
45677807Sru        n += space_length;
45777807Sru      }
45877807Sru    }
45977807Sru    ++para_line_number;
46077807Sru  }
46177807Sru  new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
46277807Sru  if (ferror(stream)) { perror(name); ++n_errors; }
4631590Srgrimes}
4641590Srgrimes
46577807Sru/* How long is the indent on this line?
4661590Srgrimes */
46777807Srustatic size_t
46877807Sruindent_length(const char *line, size_t length) {
46977807Sru  size_t n=0;
47077807Sru  while (n<length && *line++ == ' ') ++n;
47177807Sru  return n;
47277807Sru}
4731590Srgrimes
47477807Sru/* Might this line be a mail header?
47577807Sru * We deem a line to be a possible header if it matches the
47677807Sru * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
47777807Sru * as in RFC whatever-number-it-is; we want to be gratuitously
47877807Sru * conservative to avoid mangling ordinary civilised text.
4791590Srgrimes */
48077807Srustatic int
48177807Srumight_be_header(const unsigned char *line) {
48277807Sru  if (!isupper(*line++)) return 0;
48377807Sru  while (*line && (isalnum(*line) || *line=='-')) ++line;
48477807Sru  return (*line==':' && isspace(line[1]));
4851590Srgrimes}
4861590Srgrimes
48777807Sru/* Begin a new paragraph with an indent of |indent| spaces.
4881590Srgrimes */
48977807Srustatic void
49077807Srunew_paragraph(size_t old_indent, size_t indent) {
49177807Sru  if (x0) {
49277807Sru    if (old_indent>0) output_indent(old_indent);
49377807Sru    fwrite(output_buffer, 1, x0, stdout);
49477807Sru    putchar('\n');
49577807Sru  }
49677807Sru  x=indent; x0=0; pending_spaces=0;
49777807Sru  output_in_paragraph = 0;
4981590Srgrimes}
4991590Srgrimes
50077807Sru/* Output spaces or tabs for leading indentation.
5011590Srgrimes */
50277807Srustatic void
50377807Sruoutput_indent(size_t n_spaces) {
50477807Sru  if (output_tab_width) {
50577807Sru    while (n_spaces >= output_tab_width) {
50677807Sru      putchar('\t');
50777807Sru      n_spaces -= output_tab_width;
50877807Sru    }
50977807Sru  }
51077807Sru  while (n_spaces-- > 0) putchar(' ');
5111590Srgrimes}
5121590Srgrimes
51377807Sru/* Output a single word, or add it to the buffer.
51477807Sru * indent0 and indent1 are the indents to use on the first and subsequent
51577807Sru * lines of a paragraph. They'll often be the same, of course.
5161590Srgrimes */
51777807Srustatic void
51877807Sruoutput_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces) {
51977807Sru  size_t new_x = x+pending_spaces+length;
52077807Sru  size_t indent = output_in_paragraph ? indent1 : indent0;
5211590Srgrimes
52277807Sru  /* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
52377807Sru   * (squashing internal whitespace), then add just one space;
52477807Sru   * except that if the last character was a sentence-ender we
52577807Sru   * actually add two spaces.
52677807Sru   */
52777807Sru  if (coalesce_spaces_P || spaces==0)
52877807Sru    spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1;
5298874Srgrimes
53077807Sru  if (new_x<=goal_length) {
53177807Sru    /* After adding the word we still aren't at the goal length,
53277807Sru     * so clearly we add it to the buffer rather than outputing it.
53377807Sru     */
53477807Sru    memset(output_buffer+x0, ' ', pending_spaces);
53577807Sru    x0 += pending_spaces; x += pending_spaces;
53677807Sru    memcpy(output_buffer+x0, word, length);
53777807Sru    x0 += length; x += length;
53877807Sru    pending_spaces = spaces;
53977807Sru  }
54077807Sru  else {
54177807Sru    /* Adding the word takes us past the goal. Print the line-so-far,
54277807Sru     * and the word too iff either (1) the lsf is empty or (2) that
54377807Sru     * makes us nearer the goal but doesn't take us over the limit,
54477807Sru     * or (3) the word on its own takes us over the limit.
54577807Sru     * In case (3) we put a newline in between.
54677807Sru     */
54777807Sru    if (indent>0) output_indent(indent);
54877807Sru    fwrite(output_buffer, 1, x0, stdout);
54977807Sru    if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) {
55078334Sjlemon      printf("%*s", (int)pending_spaces, "");
55177807Sru      goto write_out_word;
55277807Sru    }
55377807Sru    else {
55477807Sru      /* If the word takes us over the limit on its own, just
55577807Sru       * spit it out and don't bother buffering it.
55677807Sru       */
55777807Sru      if (indent+length > max_length) {
55877807Sru        putchar('\n');
55977807Sru        if (indent>0) output_indent(indent);
56077807Sruwrite_out_word:
56177807Sru        fwrite(word, 1, length, stdout);
56277807Sru        x0 = 0; x = indent1; pending_spaces = 0;
56377807Sru      }
56477807Sru      else {
56577807Sru        memcpy(output_buffer, word, length);
56677807Sru        x0 = length; x = length+indent1; pending_spaces = spaces;
56777807Sru      }
56877807Sru    }
56977807Sru    putchar('\n');
57077807Sru    output_in_paragraph = 1;
57177807Sru  }
5721590Srgrimes}
5731590Srgrimes
57477807Sru/* Process a stream, but just center its lines rather than trying to
57577807Sru * format them neatly.
5761590Srgrimes */
57777807Srustatic void
57877807Srucenter_stream(FILE *stream, const char *name) {
57977807Sru  char *line;
58077807Sru  size_t length;
58177807Sru  while ((line=get_line(stream, &length)) != 0) {
58277807Sru    size_t l=length;
58377807Sru    while (l>0 && isspace(*line)) { ++line; --l; }
58477807Sru    length=l;
58577807Sru    while (l<goal_length) { putchar(' '); l+=2; }
58677807Sru    fwrite(line, 1, length, stdout);
58777807Sru    putchar('\n');
58877807Sru  }
58977807Sru  if (ferror(stream)) { perror(name); ++n_errors; }
5901590Srgrimes}
5911590Srgrimes
59277807Sru/* Get a single line from a stream. Expand tabs, strip control
59377807Sru * characters and trailing whitespace, and handle backspaces.
59477807Sru * Return the address of the buffer containing the line, and
59577807Sru * put the length of the line in |lengthp|.
59677807Sru * This can cope with arbitrarily long lines, and with lines
59777807Sru * without terminating \n.
59877807Sru * If there are no characters left or an error happens, we
59977807Sru * return 0.
60077807Sru * Don't confuse |spaces_pending| here with the global
60177807Sru * |pending_spaces|.
6021590Srgrimes */
60377807Srustatic char *
60477807Sruget_line(FILE *stream, size_t *lengthp) {
60577807Sru  static char *buf=NULL;
60677807Sru  static size_t length=0;
60777807Sru  size_t len=0;
60877807Sru  int ch;
60977807Sru  size_t spaces_pending=0;
61089268Sru  int troff=0;
6111590Srgrimes
61277807Sru  if (buf==NULL) { length=100; buf=XMALLOC(length); }
61377807Sru  while ((ch=getc(stream)) != '\n' && ch != EOF) {
61489268Sru    if (len+spaces_pending==0 && ch=='.' && !format_troff) troff=1;
61577807Sru    if (ch==' ') ++spaces_pending;
61689268Sru    else if (troff || isprint(ch)) {
61777807Sru      while (len+spaces_pending >= length) {
61877807Sru        length*=2; buf=xrealloc(buf, length);
61977807Sru      }
62077807Sru      while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; }
62177807Sru      buf[len++] = ch;
62277807Sru    }
62377807Sru    else if (ch=='\t')
62477807Sru      spaces_pending += tab_width - (len+spaces_pending)%tab_width;
62577807Sru    else if (ch=='\b') { if (len) --len; }
62677807Sru  }
62777807Sru  *lengthp=len;
62877807Sru  return (len>0 || ch!=EOF) ? buf : 0;
6291590Srgrimes}
6301590Srgrimes
63177807Sru/* (Re)allocate some memory, exiting with an error if we can't.
6321590Srgrimes */
63377807Srustatic void *
63477807Sruxrealloc(void *ptr, size_t nbytes) {
63577807Sru  void *p = realloc(ptr, nbytes);
63677807Sru  if (p == NULL) errx(EX_OSERR, "out of memory");
63777807Sru  return p;
6381590Srgrimes}
639