xref: /freebsd/usr.bin/fmt/fmt.c (revision 57c6bd978f417d03539a569bc132aec138825983)
11438aefcSRuslan Ermilov /*	$OpenBSD: fmt.c,v 1.16 2000/06/25 15:35:42 pjanzen 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.
331438aefcSRuslan Ermilov  * 3. The "everything else" is split into words; a word
341438aefcSRuslan Ermilov  *    includes its trailing whitespace, and a word at the
351438aefcSRuslan Ermilov  *    end of a line is deemed to be followed by a single
361438aefcSRuslan Ermilov  *    space, or two spaces if it ends with a sentence-end
371438aefcSRuslan Ermilov  *    character. (See the `-d' option for how to change that.)
381438aefcSRuslan Ermilov  *    If the `-s' option has been given, then a word's trailing
391438aefcSRuslan Ermilov  *    whitespace is replaced by what it would have had if it
401438aefcSRuslan Ermilov  *    had occurred at end of line.
411438aefcSRuslan Ermilov  * 4. Each paragraph is sent to standard output as follows.
421438aefcSRuslan Ermilov  *    We output the leading whitespace, and then enough words
431438aefcSRuslan Ermilov  *    to make the line length as near as possible to the goal
441438aefcSRuslan Ermilov  *    without exceeding the maximum. (If a single word would
451438aefcSRuslan Ermilov  *    exceed the maximum, we output that anyway.) Of course
461438aefcSRuslan Ermilov  *    the trailing whitespace of the last word is ignored.
471438aefcSRuslan Ermilov  *    We then emit a newline and start again if there are any
481438aefcSRuslan Ermilov  *    words left.
491438aefcSRuslan Ermilov  *    Note that for a blank line this translates as "We emit
501438aefcSRuslan Ermilov  *    a newline".
511438aefcSRuslan Ermilov  *    If the `-l <n>' option is given, then leading whitespace
521438aefcSRuslan Ermilov  *    is modified slightly: <n> spaces are replaced by a tab.
531438aefcSRuslan Ermilov  *    Indented paragraphs (see above under `-p') make matters
541438aefcSRuslan Ermilov  *    more complicated than this suggests. Actually every paragraph
551438aefcSRuslan Ermilov  *    has two `leading whitespace' values; the value for the first
561438aefcSRuslan Ermilov  *    line, and the value for the most recent line. (While processing
571438aefcSRuslan Ermilov  *    the first line, the two are equal. When `-p' has not been
581438aefcSRuslan Ermilov  *    given, they are always equal.) The leading whitespace
591438aefcSRuslan Ermilov  *    actually output is that of the first line (for the first
601438aefcSRuslan Ermilov  *    line of *output*) or that of the most recent line (for
611438aefcSRuslan Ermilov  *    all other lines of output).
621438aefcSRuslan Ermilov  *    When `-m' has been given, message header paragraphs are
631438aefcSRuslan Ermilov  *    taken as having first-leading-whitespace empty and
641438aefcSRuslan Ermilov  *    subsequent-leading-whitespace two spaces.
651438aefcSRuslan Ermilov  *
661438aefcSRuslan Ermilov  * Multiple input files are formatted one at a time, so that a file
671438aefcSRuslan Ermilov  * never ends in the middle of a line.
681438aefcSRuslan Ermilov  *
691438aefcSRuslan Ermilov  * There's an alternative mode of operation, invoked by giving
701438aefcSRuslan Ermilov  * the `-c' option. In that case we just center every line,
711438aefcSRuslan Ermilov  * and most of the other options are ignored. This should
721438aefcSRuslan Ermilov  * really be in a separate program, but we must stay compatible
731438aefcSRuslan Ermilov  * with old `fmt'.
741438aefcSRuslan Ermilov  *
751438aefcSRuslan Ermilov  * QUERY: Should `-m' also try to do the right thing with quoted text?
761438aefcSRuslan Ermilov  * QUERY: `-b' to treat backslashed whitespace as old `fmt' does?
771438aefcSRuslan Ermilov  * QUERY: Option meaning `never join lines'?
781438aefcSRuslan Ermilov  * QUERY: Option meaning `split in mid-word to avoid overlong lines'?
791438aefcSRuslan Ermilov  * (Those last two might not be useful, since we have `fold'.)
801438aefcSRuslan Ermilov  *
811438aefcSRuslan Ermilov  * Differences from old `fmt':
821438aefcSRuslan Ermilov  *
831438aefcSRuslan Ermilov  *   - We have many more options. Options that aren't understood
841438aefcSRuslan Ermilov  *     generate a lengthy usage message, rather than being
851438aefcSRuslan Ermilov  *     treated as filenames.
861438aefcSRuslan Ermilov  *   - Even with `-m', our handling of message headers is
871438aefcSRuslan Ermilov  *     significantly different. (And much better.)
881438aefcSRuslan Ermilov  *   - We don't treat `\ ' as non-word-breaking.
891438aefcSRuslan Ermilov  *   - Downward changes of indentation start new paragraphs
901438aefcSRuslan Ermilov  *     for us, as well as upward. (I think old `fmt' behaves
911438aefcSRuslan Ermilov  *     in the way it does in order to allow indented paragraphs,
921438aefcSRuslan Ermilov  *     but this is a broken way of making indented paragraphs
931438aefcSRuslan Ermilov  *     behave right.)
941438aefcSRuslan Ermilov  *   - Given the choice of going over or under |goal_length|
951438aefcSRuslan Ermilov  *     by the same amount, we go over; old `fmt' goes under.
961438aefcSRuslan Ermilov  *   - We treat `?' as ending a sentence, and not `:'. Old `fmt'
971438aefcSRuslan Ermilov  *     does the reverse.
981438aefcSRuslan Ermilov  *   - We return approved return codes. Old `fmt' returns
991438aefcSRuslan Ermilov  *     1 for some errors, and *the number of unopenable files*
1001438aefcSRuslan Ermilov  *     when that was all that went wrong.
1011438aefcSRuslan Ermilov  *   - We have fewer crashes and more helpful error messages.
1021438aefcSRuslan Ermilov  *   - We don't turn spaces into tabs at starts of lines unless
1031438aefcSRuslan Ermilov  *     specifically requested.
1041438aefcSRuslan Ermilov  *   - New `fmt' is somewhat smaller and slightly faster than
1051438aefcSRuslan Ermilov  *     old `fmt'.
1061438aefcSRuslan Ermilov  *
1071438aefcSRuslan Ermilov  * Bugs:
1081438aefcSRuslan Ermilov  *
1091438aefcSRuslan Ermilov  *   None known. There probably are some, though.
1101438aefcSRuslan Ermilov  *
1111438aefcSRuslan Ermilov  * Portability:
1121438aefcSRuslan Ermilov  *
1131438aefcSRuslan Ermilov  *   I believe this code to be pretty portable. It does require
1141438aefcSRuslan Ermilov  *   that you have `getopt'. If you need to include "getopt.h"
1151438aefcSRuslan Ermilov  *   for this (e.g., if your system didn't come with `getopt'
1161438aefcSRuslan Ermilov  *   and you installed it yourself) then you should arrange for
1171438aefcSRuslan Ermilov  *   NEED_getopt_h to be #defined.
1181438aefcSRuslan Ermilov  *
1191438aefcSRuslan Ermilov  *   Everything here should work OK even on nasty 16-bit
1201438aefcSRuslan Ermilov  *   machines and nice 64-bit ones. However, it's only really
1211438aefcSRuslan Ermilov  *   been tested on my FreeBSD machine. Your mileage may vary.
1221438aefcSRuslan Ermilov  */
1231438aefcSRuslan Ermilov 
1241438aefcSRuslan Ermilov /* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
1251438aefcSRuslan Ermilov  *
1261438aefcSRuslan Ermilov  * Redistribution and use of this code, in source or binary forms,
1271438aefcSRuslan Ermilov  * with or without modification, are permitted subject to the following
1281438aefcSRuslan Ermilov  * conditions:
1291438aefcSRuslan Ermilov  *
1301438aefcSRuslan Ermilov  *  - Redistribution of source code must retain the above copyright
1319b50d902SRodney W. Grimes  *    notice, this list of conditions and the following disclaimer.
1329b50d902SRodney W. Grimes  *
1331438aefcSRuslan Ermilov  *  - If you distribute modified source code it must also include
1341438aefcSRuslan Ermilov  *    a notice saying that it has been modified, and giving a brief
1351438aefcSRuslan Ermilov  *    description of what changes have been made.
1361438aefcSRuslan Ermilov  *
1371438aefcSRuslan Ermilov  * Disclaimer: I am not responsible for the results of using this code.
1381438aefcSRuslan Ermilov  *             If it formats your hard disc, sends obscene messages to
1391438aefcSRuslan Ermilov  *             your boss and kills your children then that's your problem
1401438aefcSRuslan Ermilov  *             not mine. I give absolutely no warranty of any sort as to
1411438aefcSRuslan Ermilov  *             what the program will do, and absolutely refuse to be held
1421438aefcSRuslan Ermilov  *             liable for any consequences of your using it.
1431438aefcSRuslan Ermilov  *             Thank you. Have a nice day.
1441438aefcSRuslan Ermilov  */
1451438aefcSRuslan Ermilov 
1461438aefcSRuslan Ermilov /* RCS change log:
1471438aefcSRuslan Ermilov  * Revision 1.5  1998/03/02 18:02:21  gjm11
1481438aefcSRuslan Ermilov  * Minor changes for portability.
1491438aefcSRuslan Ermilov  *
1501438aefcSRuslan Ermilov  * Revision 1.4  1997/10/01 11:51:28  gjm11
1511438aefcSRuslan Ermilov  * Repair broken indented-paragraph handling.
1521438aefcSRuslan Ermilov  * Add mail message header stuff.
1531438aefcSRuslan Ermilov  * Improve comments and layout.
1541438aefcSRuslan Ermilov  * Make usable with non-BSD systems.
1551438aefcSRuslan Ermilov  * Add revision display to usage message.
1561438aefcSRuslan Ermilov  *
1571438aefcSRuslan Ermilov  * Revision 1.3  1997/09/30 16:24:47  gjm11
1581438aefcSRuslan Ermilov  * Add copyright notice, rcsid string and log message.
1591438aefcSRuslan Ermilov  *
1601438aefcSRuslan Ermilov  * Revision 1.2  1997/09/30 16:13:39  gjm11
1611438aefcSRuslan Ermilov  * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h .
1621438aefcSRuslan Ermilov  * Parse options with `getopt'. Clean up code generally.
1631438aefcSRuslan Ermilov  * Make comments more accurate.
1641438aefcSRuslan Ermilov  *
1651438aefcSRuslan Ermilov  * Revision 1.1  1997/09/30 11:29:57  gjm11
1661438aefcSRuslan Ermilov  * Initial revision
1679b50d902SRodney W. Grimes  */
1689b50d902SRodney W. Grimes 
1699b50d902SRodney W. Grimes #ifndef lint
17063ffb113SPhilippe Charnier static const char rcsid[] =
171c3aac50fSPeter Wemm   "$FreeBSD$";
1721438aefcSRuslan Ermilov static const char copyright[] =
1731438aefcSRuslan Ermilov   "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n";
1749b50d902SRodney W. Grimes #endif /* not lint */
1759b50d902SRodney W. Grimes 
1769b50d902SRodney W. Grimes #include <ctype.h>
17763ffb113SPhilippe Charnier #include <err.h>
1788bbd9072SAndrey A. Chernov #include <locale.h>
17963ffb113SPhilippe Charnier #include <stdio.h>
180e6c267f1SJoerg Wunsch #include <stdlib.h>
18163ffb113SPhilippe Charnier #include <string.h>
1821438aefcSRuslan Ermilov #include <sysexits.h>
1831438aefcSRuslan Ermilov #include <unistd.h>
1849b50d902SRodney W. Grimes 
1851438aefcSRuslan Ermilov /* Something that, we hope, will never be a genuine line length,
1861438aefcSRuslan Ermilov  * indentation etc.
1879b50d902SRodney W. Grimes  */
1881438aefcSRuslan Ermilov #define SILLY ((size_t)-1)
1899b50d902SRodney W. Grimes 
1901438aefcSRuslan Ermilov /* I used to use |strtoul| for this, but (1) not all systems have it
1911438aefcSRuslan Ermilov  * and (2) it's probably better to use |strtol| to detect negative
1921438aefcSRuslan Ermilov  * numbers better.
1931438aefcSRuslan Ermilov  * If |fussyp==0| then we don't complain about non-numbers
1941438aefcSRuslan Ermilov  * (returning 0 instead), but we do complain about bad numbers.
1959b50d902SRodney W. Grimes  */
1961438aefcSRuslan Ermilov static size_t
1971438aefcSRuslan Ermilov get_positive(const char *s, const char *err_mess, int fussyP) {
1981438aefcSRuslan Ermilov   char *t;
1991438aefcSRuslan Ermilov   long result = strtol(s,&t,0);
2001438aefcSRuslan Ermilov   if (*t) { if (fussyP) goto Lose; else return 0; }
20157c6bd97SKris Kennaway   if (result<=0) { Lose: errx(EX_USAGE, "%s", err_mess); }
2021438aefcSRuslan Ermilov   return (size_t) result;
2031438aefcSRuslan Ermilov }
2049b50d902SRodney W. Grimes 
2051438aefcSRuslan Ermilov /* Global variables */
2069b50d902SRodney W. Grimes 
2071438aefcSRuslan Ermilov static int centerP=0;		/* Try to center lines? */
2081438aefcSRuslan Ermilov static size_t goal_length=0;	/* Target length for output lines */
2091438aefcSRuslan Ermilov static size_t max_length=0;	/* Maximum length for output lines */
2101438aefcSRuslan Ermilov static int coalesce_spaces_P=0;	/* Coalesce multiple whitespace -> ' ' ? */
2111438aefcSRuslan Ermilov static int allow_indented_paragraphs=0;	/* Can first line have diff. ind.? */
2121438aefcSRuslan Ermilov static int tab_width=8;		/* Number of spaces per tab stop */
2131438aefcSRuslan Ermilov static size_t output_tab_width=0;	/* Ditto, when squashing leading spaces */
2141438aefcSRuslan Ermilov static const char *sentence_enders=".?!";	/* Double-space after these */
2151438aefcSRuslan Ermilov static int grok_mail_headers=0;	/* treat embedded mail headers magically? */
2169b50d902SRodney W. Grimes 
2171438aefcSRuslan Ermilov static int n_errors=0;		/* Number of failed files. Return on exit. */
2181438aefcSRuslan Ermilov static char *output_buffer=0;	/* Output line will be built here */
2191438aefcSRuslan Ermilov static size_t x;		/* Horizontal position in output line */
2201438aefcSRuslan Ermilov static size_t x0;		/* Ditto, ignoring leading whitespace */
2211438aefcSRuslan Ermilov static size_t pending_spaces;	/* Spaces to add before next word */
2221438aefcSRuslan Ermilov static int output_in_paragraph=0;	/* Any of current para written out yet? */
22363ffb113SPhilippe Charnier 
2241438aefcSRuslan Ermilov /* Prototypes */
2251438aefcSRuslan Ermilov 
2261438aefcSRuslan Ermilov static void process_named_file (const char *);
2271438aefcSRuslan Ermilov static void     process_stream (FILE *, const char *);
2281438aefcSRuslan Ermilov static size_t    indent_length (const char *, size_t);
2291438aefcSRuslan Ermilov static int     might_be_header (const unsigned char *);
2301438aefcSRuslan Ermilov static void      new_paragraph (size_t, size_t);
2311438aefcSRuslan Ermilov static void        output_word (size_t, size_t, const char *, size_t, size_t);
2321438aefcSRuslan Ermilov static void      output_indent (size_t);
2331438aefcSRuslan Ermilov static void      center_stream (FILE *, const char *);
2341438aefcSRuslan Ermilov static char *         get_line (FILE *, size_t *);
2351438aefcSRuslan Ermilov static void *         xrealloc (void *, size_t);
2361438aefcSRuslan Ermilov 
2371438aefcSRuslan Ermilov #define XMALLOC(x) xrealloc(0,x)
2381438aefcSRuslan Ermilov 
2391438aefcSRuslan Ermilov /* Here is perhaps the right place to mention that this code is
2401438aefcSRuslan Ermilov  * all in top-down order. Hence, |main| comes first.
2419b50d902SRodney W. Grimes  */
24263ffb113SPhilippe Charnier int
2431438aefcSRuslan Ermilov main(int argc, char *argv[]) {
2441438aefcSRuslan Ermilov   int ch;			/* used for |getopt| processing */
2451438aefcSRuslan Ermilov 
2469b50d902SRodney W. Grimes 
2478bbd9072SAndrey A. Chernov   (void) setlocale(LC_CTYPE, "");
2488bbd9072SAndrey A. Chernov 
2491438aefcSRuslan Ermilov   /* 1. Grok parameters. */
2501438aefcSRuslan Ermilov 
2511438aefcSRuslan Ermilov   while ((ch = getopt(argc, argv, "0123456789cd:hl:mpst:w:")) != -1)
2521438aefcSRuslan Ermilov   switch(ch) {
2531438aefcSRuslan Ermilov     case 'c':
2541438aefcSRuslan Ermilov       centerP = 1;
2551438aefcSRuslan Ermilov       continue;
2561438aefcSRuslan Ermilov     case 'd':
2571438aefcSRuslan Ermilov       sentence_enders = optarg;
2581438aefcSRuslan Ermilov       continue;
2591438aefcSRuslan Ermilov     case 'l':
2601438aefcSRuslan Ermilov       output_tab_width
2611438aefcSRuslan Ermilov         = get_positive(optarg, "output tab width must be positive", 1);
2621438aefcSRuslan Ermilov       continue;
2631438aefcSRuslan Ermilov     case 'm':
2641438aefcSRuslan Ermilov       grok_mail_headers = 1;
2651438aefcSRuslan Ermilov       continue;
2661438aefcSRuslan Ermilov     case 'p':
2671438aefcSRuslan Ermilov       allow_indented_paragraphs = 1;
2681438aefcSRuslan Ermilov       continue;
2691438aefcSRuslan Ermilov     case 's':
2701438aefcSRuslan Ermilov       coalesce_spaces_P = 1;
2711438aefcSRuslan Ermilov       continue;
2721438aefcSRuslan Ermilov     case 't':
2731438aefcSRuslan Ermilov       tab_width = get_positive(optarg, "tab width must be positive", 1);
2741438aefcSRuslan Ermilov       continue;
2751438aefcSRuslan Ermilov     case 'w':
2761438aefcSRuslan Ermilov       goal_length = get_positive(optarg, "width must be positive", 1);
2771438aefcSRuslan Ermilov       max_length = goal_length;
2781438aefcSRuslan Ermilov       continue;
2791438aefcSRuslan Ermilov     case '0': case '1': case '2': case '3': case '4': case '5':
2801438aefcSRuslan Ermilov     case '6': case '7': case '8': case '9':
2811438aefcSRuslan Ermilov     /* XXX  this is not a stylistically approved use of getopt() */
2821438aefcSRuslan Ermilov       if (goal_length==0) {
2831438aefcSRuslan Ermilov         char *p;
2841438aefcSRuslan Ermilov         p = argv[optind - 1];
2851438aefcSRuslan Ermilov         if (p[0] == '-' && p[1] == ch && !p[2])
2861438aefcSRuslan Ermilov              goal_length = get_positive(++p, "width must be nonzero", 1);
2871438aefcSRuslan Ermilov         else
2881438aefcSRuslan Ermilov              goal_length = get_positive(argv[optind]+1,
2891438aefcSRuslan Ermilov                  "width must be nonzero", 1);
2901438aefcSRuslan Ermilov         max_length = goal_length;
2911438aefcSRuslan Ermilov       }
2921438aefcSRuslan Ermilov       continue;
2931438aefcSRuslan Ermilov     case 'h': default:
2941438aefcSRuslan Ermilov       fprintf(stderr,
2951438aefcSRuslan Ermilov "Usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
2961438aefcSRuslan Ermilov "             [-w width | -width | goal [maximum]] [file ...]\n"
2971438aefcSRuslan Ermilov "Options: -c     center each line instead of formatting\n"
2981438aefcSRuslan Ermilov "         -d <chars> double-space after <chars> at line end\n"
2991438aefcSRuslan Ermilov "         -l <n> turn each <n> spaces at start of line into a tab\n"
3001438aefcSRuslan Ermilov "         -m     try to make sure mail header lines stay separate\n"
3011438aefcSRuslan Ermilov "         -p     allow indented paragraphs\n"
3021438aefcSRuslan Ermilov "         -s     coalesce whitespace inside lines\n"
3031438aefcSRuslan Ermilov "         -t <n> have tabs every <n> columns\n"
3041438aefcSRuslan Ermilov "         -w <n> set maximum width to <n>\n"
3051438aefcSRuslan Ermilov "         goal   set target width to goal\n");
3061438aefcSRuslan Ermilov       exit(ch=='h' ? 0 : EX_USAGE);
3071438aefcSRuslan Ermilov   }
3081438aefcSRuslan Ermilov   argc -= optind; argv += optind;
3091438aefcSRuslan Ermilov 
3101438aefcSRuslan Ermilov   /* [ goal [ maximum ] ] */
3111438aefcSRuslan Ermilov 
3121438aefcSRuslan Ermilov   if (argc>0 && goal_length==0
3131438aefcSRuslan Ermilov       && (goal_length=get_positive(*argv,"goal length must be positive", 0))
3141438aefcSRuslan Ermilov          != 0) {
3151438aefcSRuslan Ermilov     --argc; ++argv;
3161438aefcSRuslan Ermilov     if (argc>0
3171438aefcSRuslan Ermilov         && (max_length=get_positive(*argv,"max length must be positive", 0))
3181438aefcSRuslan Ermilov            != 0) {
3191438aefcSRuslan Ermilov       --argc; ++argv;
3201438aefcSRuslan Ermilov       if (max_length<goal_length)
3211438aefcSRuslan Ermilov         errx(EX_USAGE, "max length must be >= goal length");
3221438aefcSRuslan Ermilov     }
3231438aefcSRuslan Ermilov   }
3241438aefcSRuslan Ermilov   if (goal_length==0) goal_length = 65;
3251438aefcSRuslan Ermilov   if (max_length==0) max_length = goal_length+10;
3261438aefcSRuslan Ermilov   output_buffer = XMALLOC(max_length+1);	/* really needn't be longer */
3271438aefcSRuslan Ermilov 
3281438aefcSRuslan Ermilov   /* 2. Process files. */
3291438aefcSRuslan Ermilov 
3301438aefcSRuslan Ermilov   if (argc>0) {
3311438aefcSRuslan Ermilov     while (argc-->0) process_named_file(*argv++);
3321438aefcSRuslan Ermilov   }
3331438aefcSRuslan Ermilov   else {
3341438aefcSRuslan Ermilov     process_stream(stdin, "standard input");
3351438aefcSRuslan Ermilov   }
3361438aefcSRuslan Ermilov 
3371438aefcSRuslan Ermilov   /* We're done. */
3381438aefcSRuslan Ermilov 
3391438aefcSRuslan Ermilov   return n_errors ? EX_NOINPUT : 0;
3401438aefcSRuslan Ermilov 
3411438aefcSRuslan Ermilov }
3421438aefcSRuslan Ermilov 
3431438aefcSRuslan Ermilov /* Process a single file, given its name.
3449b50d902SRodney W. Grimes  */
3451438aefcSRuslan Ermilov static void
3461438aefcSRuslan Ermilov process_named_file(const char *name) {
3471438aefcSRuslan Ermilov   FILE *f=fopen(name, "r");
3481438aefcSRuslan Ermilov   if (!f) { perror(name); ++n_errors; }
3491438aefcSRuslan Ermilov   else {
3501438aefcSRuslan Ermilov     process_stream(f, name);
3511438aefcSRuslan Ermilov     fclose(f);
3529b50d902SRodney W. Grimes   }
3539b50d902SRodney W. Grimes }
3541438aefcSRuslan Ermilov 
3551438aefcSRuslan Ermilov /* Types of mail header continuation lines:
3561438aefcSRuslan Ermilov  */
3571438aefcSRuslan Ermilov typedef enum {
3581438aefcSRuslan Ermilov   hdr_ParagraphStart = -1,
3591438aefcSRuslan Ermilov   hdr_NonHeader      = 0,
3601438aefcSRuslan Ermilov   hdr_Header         = 1,
3611438aefcSRuslan Ermilov   hdr_Continuation   = 2
3621438aefcSRuslan Ermilov } HdrType;
3631438aefcSRuslan Ermilov 
3641438aefcSRuslan Ermilov /* Process a stream. This is where the real work happens,
3651438aefcSRuslan Ermilov  * except that centering is handled separately.
3661438aefcSRuslan Ermilov  */
3671438aefcSRuslan Ermilov static void
3681438aefcSRuslan Ermilov process_stream(FILE *stream, const char *name) {
3691438aefcSRuslan Ermilov   size_t last_indent=SILLY;	/* how many spaces in last indent? */
3701438aefcSRuslan Ermilov   size_t para_line_number=0;	/* how many lines already read in this para? */
3711438aefcSRuslan Ermilov   size_t first_indent=SILLY;	/* indentation of line 0 of paragraph */
3721438aefcSRuslan Ermilov   HdrType prev_header_type=hdr_ParagraphStart;
3731438aefcSRuslan Ermilov 	/* ^-- header_type of previous line; -1 at para start */
3741438aefcSRuslan Ermilov   char *line;
3751438aefcSRuslan Ermilov   size_t length;
3761438aefcSRuslan Ermilov 
3771438aefcSRuslan Ermilov   if (centerP) { center_stream(stream, name); return; }
3781438aefcSRuslan Ermilov   while ((line=get_line(stream,&length)) != NULL) {
3791438aefcSRuslan Ermilov     size_t np=indent_length(line, length);
3801438aefcSRuslan Ermilov     { HdrType header_type=hdr_NonHeader;
3811438aefcSRuslan Ermilov       if (grok_mail_headers && prev_header_type!=hdr_NonHeader) {
3821438aefcSRuslan Ermilov         if (np==0 && might_be_header(line))
3831438aefcSRuslan Ermilov           header_type = hdr_Header;
3841438aefcSRuslan Ermilov         else if (np>0 && prev_header_type>hdr_NonHeader)
3851438aefcSRuslan Ermilov           header_type = hdr_Continuation;
3869b50d902SRodney W. Grimes       }
3871438aefcSRuslan Ermilov       /* We need a new paragraph if and only if:
3881438aefcSRuslan Ermilov        *   this line is blank,
3891438aefcSRuslan Ermilov        *   OR it's a mail header,
3901438aefcSRuslan Ermilov        *   OR it's not a mail header AND the last line was one,
3911438aefcSRuslan Ermilov        *   OR the indentation has changed
3921438aefcSRuslan Ermilov        *      AND the line isn't a mail header continuation line
3931438aefcSRuslan Ermilov        *      AND this isn't the second line of an indented paragraph.
3941438aefcSRuslan Ermilov        */
3951438aefcSRuslan Ermilov       if ( length==0
3961438aefcSRuslan Ermilov            || header_type==hdr_Header
3971438aefcSRuslan Ermilov            || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader)
3981438aefcSRuslan Ermilov            || (np!=last_indent
3991438aefcSRuslan Ermilov                && header_type != hdr_Continuation
4001438aefcSRuslan Ermilov                && (!allow_indented_paragraphs || para_line_number != 1)) ) {
4011438aefcSRuslan Ermilov         new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
4021438aefcSRuslan Ermilov         para_line_number = 0;
4031438aefcSRuslan Ermilov         first_indent = np;
4041438aefcSRuslan Ermilov         last_indent = np;
4051438aefcSRuslan Ermilov         if (header_type==hdr_Header) last_indent=2;	/* for cont. lines */
4061438aefcSRuslan Ermilov         if (length==0) {
4071438aefcSRuslan Ermilov           putchar('\n');
4081438aefcSRuslan Ermilov           prev_header_type=hdr_ParagraphStart;
4099b50d902SRodney W. Grimes           continue;
4109b50d902SRodney W. Grimes         }
4119b50d902SRodney W. Grimes       }
4121438aefcSRuslan Ermilov       else {
4131438aefcSRuslan Ermilov         /* If this is an indented paragraph other than a mail header
4141438aefcSRuslan Ermilov          * continuation, set |last_indent|.
4159b50d902SRodney W. Grimes          */
4161438aefcSRuslan Ermilov         if (np != last_indent && header_type != hdr_Continuation)
4171438aefcSRuslan Ermilov           last_indent=np;
4181438aefcSRuslan Ermilov       }
4191438aefcSRuslan Ermilov       prev_header_type = header_type;
4201438aefcSRuslan Ermilov     }
421dc3001cfSJonathan Lemon 
4221438aefcSRuslan Ermilov     { size_t n=np;
4231438aefcSRuslan Ermilov       while (n<length) {
4241438aefcSRuslan Ermilov         /* Find word end and count spaces after it */
4251438aefcSRuslan Ermilov         size_t word_length=0, space_length=0;
4261438aefcSRuslan Ermilov         while (n+word_length < length && line[n+word_length] != ' ')
4271438aefcSRuslan Ermilov           ++word_length;
4281438aefcSRuslan Ermilov         space_length = word_length;
4291438aefcSRuslan Ermilov         while (n+space_length < length && line[n+space_length] == ' ')
4301438aefcSRuslan Ermilov           ++space_length;
4311438aefcSRuslan Ermilov         /* Send the word to the output machinery. */
4321438aefcSRuslan Ermilov         output_word(first_indent, last_indent,
4331438aefcSRuslan Ermilov                     line+n, word_length, space_length-word_length);
4341438aefcSRuslan Ermilov         n += space_length;
4351438aefcSRuslan Ermilov       }
4361438aefcSRuslan Ermilov     }
4371438aefcSRuslan Ermilov     ++para_line_number;
4381438aefcSRuslan Ermilov   }
4391438aefcSRuslan Ermilov   new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
4401438aefcSRuslan Ermilov   if (ferror(stream)) { perror(name); ++n_errors; }
4411438aefcSRuslan Ermilov }
4429b50d902SRodney W. Grimes 
4431438aefcSRuslan Ermilov /* How long is the indent on this line?
4441438aefcSRuslan Ermilov  */
4451438aefcSRuslan Ermilov static size_t
4461438aefcSRuslan Ermilov indent_length(const char *line, size_t length) {
4471438aefcSRuslan Ermilov   size_t n=0;
4481438aefcSRuslan Ermilov   while (n<length && *line++ == ' ') ++n;
4491438aefcSRuslan Ermilov   return n;
4501438aefcSRuslan Ermilov }
4511438aefcSRuslan Ermilov 
4521438aefcSRuslan Ermilov /* Might this line be a mail header?
4531438aefcSRuslan Ermilov  * We deem a line to be a possible header if it matches the
4541438aefcSRuslan Ermilov  * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
4551438aefcSRuslan Ermilov  * as in RFC whatever-number-it-is; we want to be gratuitously
4561438aefcSRuslan Ermilov  * conservative to avoid mangling ordinary civilised text.
4571438aefcSRuslan Ermilov  */
4581438aefcSRuslan Ermilov static int
4591438aefcSRuslan Ermilov might_be_header(const unsigned char *line) {
4601438aefcSRuslan Ermilov   if (!isupper(*line++)) return 0;
4611438aefcSRuslan Ermilov   while (*line && (isalnum(*line) || *line=='-')) ++line;
4621438aefcSRuslan Ermilov   return (*line==':' && isspace(line[1]));
4631438aefcSRuslan Ermilov }
4641438aefcSRuslan Ermilov 
4651438aefcSRuslan Ermilov /* Begin a new paragraph with an indent of |indent| spaces.
4661438aefcSRuslan Ermilov  */
4671438aefcSRuslan Ermilov static void
4681438aefcSRuslan Ermilov new_paragraph(size_t old_indent, size_t indent) {
4691438aefcSRuslan Ermilov   if (x0) {
4701438aefcSRuslan Ermilov     if (old_indent>0) output_indent(old_indent);
4711438aefcSRuslan Ermilov     fwrite(output_buffer, 1, x0, stdout);
4723f8da92bSPoul-Henning Kamp     putchar('\n');
4733f8da92bSPoul-Henning Kamp   }
4741438aefcSRuslan Ermilov   x=indent; x0=0; pending_spaces=0;
4751438aefcSRuslan Ermilov   output_in_paragraph = 0;
4769b50d902SRodney W. Grimes }
4779b50d902SRodney W. Grimes 
4781438aefcSRuslan Ermilov /* Output spaces or tabs for leading indentation.
4799b50d902SRodney W. Grimes  */
4801438aefcSRuslan Ermilov static void
4811438aefcSRuslan Ermilov output_indent(size_t n_spaces) {
4821438aefcSRuslan Ermilov   if (output_tab_width) {
4831438aefcSRuslan Ermilov     while (n_spaces >= output_tab_width) {
4841438aefcSRuslan Ermilov       putchar('\t');
4851438aefcSRuslan Ermilov       n_spaces -= output_tab_width;
4861438aefcSRuslan Ermilov     }
4871438aefcSRuslan Ermilov   }
4881438aefcSRuslan Ermilov   while (n_spaces-- > 0) putchar(' ');
4891438aefcSRuslan Ermilov }
4909b50d902SRodney W. Grimes 
4911438aefcSRuslan Ermilov /* Output a single word, or add it to the buffer.
4921438aefcSRuslan Ermilov  * indent0 and indent1 are the indents to use on the first and subsequent
4931438aefcSRuslan Ermilov  * lines of a paragraph. They'll often be the same, of course.
4941438aefcSRuslan Ermilov  */
4951438aefcSRuslan Ermilov static void
4961438aefcSRuslan Ermilov output_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces) {
4971438aefcSRuslan Ermilov   size_t new_x = x+pending_spaces+length;
4981438aefcSRuslan Ermilov   size_t indent = output_in_paragraph ? indent1 : indent0;
4991438aefcSRuslan Ermilov 
5001438aefcSRuslan Ermilov   /* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
5011438aefcSRuslan Ermilov    * (squashing internal whitespace), then add just one space;
5021438aefcSRuslan Ermilov    * except that if the last character was a sentence-ender we
5031438aefcSRuslan Ermilov    * actually add two spaces.
5041438aefcSRuslan Ermilov    */
5051438aefcSRuslan Ermilov   if (coalesce_spaces_P || spaces==0)
5061438aefcSRuslan Ermilov     spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1;
5071438aefcSRuslan Ermilov 
5081438aefcSRuslan Ermilov   if (new_x<=goal_length) {
5091438aefcSRuslan Ermilov     /* After adding the word we still aren't at the goal length,
5101438aefcSRuslan Ermilov      * so clearly we add it to the buffer rather than outputing it.
5111438aefcSRuslan Ermilov      */
5121438aefcSRuslan Ermilov     memset(output_buffer+x0, ' ', pending_spaces);
5131438aefcSRuslan Ermilov     x0 += pending_spaces; x += pending_spaces;
5141438aefcSRuslan Ermilov     memcpy(output_buffer+x0, word, length);
5151438aefcSRuslan Ermilov     x0 += length; x += length;
5161438aefcSRuslan Ermilov     pending_spaces = spaces;
5171438aefcSRuslan Ermilov   }
5181438aefcSRuslan Ermilov   else {
5191438aefcSRuslan Ermilov     /* Adding the word takes us past the goal. Print the line-so-far,
5201438aefcSRuslan Ermilov      * and the word too iff either (1) the lsf is empty or (2) that
5211438aefcSRuslan Ermilov      * makes us nearer the goal but doesn't take us over the limit,
5221438aefcSRuslan Ermilov      * or (3) the word on its own takes us over the limit.
5231438aefcSRuslan Ermilov      * In case (3) we put a newline in between.
5241438aefcSRuslan Ermilov      */
5251438aefcSRuslan Ermilov     if (indent>0) output_indent(indent);
5261438aefcSRuslan Ermilov     fwrite(output_buffer, 1, x0, stdout);
5271438aefcSRuslan Ermilov     if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) {
52884982751SJonathan Lemon       printf("%*s", (int)pending_spaces, "");
5291438aefcSRuslan Ermilov       goto write_out_word;
5301438aefcSRuslan Ermilov     }
5311438aefcSRuslan Ermilov     else {
5321438aefcSRuslan Ermilov       /* If the word takes us over the limit on its own, just
5331438aefcSRuslan Ermilov        * spit it out and don't bother buffering it.
5341438aefcSRuslan Ermilov        */
5351438aefcSRuslan Ermilov       if (indent+length > max_length) {
536003aaef8SSujal Patel         putchar('\n');
5371438aefcSRuslan Ermilov         if (indent>0) output_indent(indent);
5381438aefcSRuslan Ermilov write_out_word:
5391438aefcSRuslan Ermilov         fwrite(word, 1, length, stdout);
5401438aefcSRuslan Ermilov         x0 = 0; x = indent1; pending_spaces = 0;
541003aaef8SSujal Patel       }
5421438aefcSRuslan Ermilov       else {
5431438aefcSRuslan Ermilov         memcpy(output_buffer, word, length);
5441438aefcSRuslan Ermilov         x0 = length; x = length+indent1; pending_spaces = spaces;
5459b50d902SRodney W. Grimes       }
5469b50d902SRodney W. Grimes     }
5479b50d902SRodney W. Grimes     putchar('\n');
5481438aefcSRuslan Ermilov     output_in_paragraph = 1;
5499c61e111SJoerg Wunsch   }
5509c61e111SJoerg Wunsch }
5519c61e111SJoerg Wunsch 
5521438aefcSRuslan Ermilov /* Process a stream, but just center its lines rather than trying to
5531438aefcSRuslan Ermilov  * format them neatly.
5549b50d902SRodney W. Grimes  */
5551438aefcSRuslan Ermilov static void
5561438aefcSRuslan Ermilov center_stream(FILE *stream, const char *name) {
5571438aefcSRuslan Ermilov   char *line;
5581438aefcSRuslan Ermilov   size_t length;
5591438aefcSRuslan Ermilov   while ((line=get_line(stream, &length)) != 0) {
5601438aefcSRuslan Ermilov     size_t l=length;
5611438aefcSRuslan Ermilov     while (l>0 && isspace(*line)) { ++line; --l; }
5621438aefcSRuslan Ermilov     length=l;
5631438aefcSRuslan Ermilov     while (l<goal_length) { putchar(' '); l+=2; }
5641438aefcSRuslan Ermilov     fwrite(line, 1, length, stdout);
5651438aefcSRuslan Ermilov     putchar('\n');
5661438aefcSRuslan Ermilov   }
5671438aefcSRuslan Ermilov   if (ferror(stream)) { perror(name); ++n_errors; }
5689b50d902SRodney W. Grimes }
5699b50d902SRodney W. Grimes 
5701438aefcSRuslan Ermilov /* Get a single line from a stream. Expand tabs, strip control
5711438aefcSRuslan Ermilov  * characters and trailing whitespace, and handle backspaces.
5721438aefcSRuslan Ermilov  * Return the address of the buffer containing the line, and
5731438aefcSRuslan Ermilov  * put the length of the line in |lengthp|.
5741438aefcSRuslan Ermilov  * This can cope with arbitrarily long lines, and with lines
5751438aefcSRuslan Ermilov  * without terminating \n.
5761438aefcSRuslan Ermilov  * If there are no characters left or an error happens, we
5771438aefcSRuslan Ermilov  * return 0.
5781438aefcSRuslan Ermilov  * Don't confuse |spaces_pending| here with the global
5791438aefcSRuslan Ermilov  * |pending_spaces|.
5809b50d902SRodney W. Grimes  */
5811438aefcSRuslan Ermilov static char *
5821438aefcSRuslan Ermilov get_line(FILE *stream, size_t *lengthp) {
5831438aefcSRuslan Ermilov   static char *buf=NULL;
5841438aefcSRuslan Ermilov   static size_t length=0;
5851438aefcSRuslan Ermilov   size_t len=0;
5861438aefcSRuslan Ermilov   int ch;
5871438aefcSRuslan Ermilov   size_t spaces_pending=0;
5881438aefcSRuslan Ermilov 
5891438aefcSRuslan Ermilov   if (buf==NULL) { length=100; buf=XMALLOC(length); }
5901438aefcSRuslan Ermilov   while ((ch=getc(stream)) != '\n' && ch != EOF) {
5911438aefcSRuslan Ermilov     if (ch==' ') ++spaces_pending;
5921438aefcSRuslan Ermilov     else if (isprint(ch)) {
5931438aefcSRuslan Ermilov       while (len+spaces_pending >= length) {
5941438aefcSRuslan Ermilov         length*=2; buf=xrealloc(buf, length);
5959b50d902SRodney W. Grimes       }
5961438aefcSRuslan Ermilov       while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; }
5971438aefcSRuslan Ermilov       buf[len++] = ch;
5989b50d902SRodney W. Grimes     }
5991438aefcSRuslan Ermilov     else if (ch=='\t')
6001438aefcSRuslan Ermilov       spaces_pending += tab_width - (len+spaces_pending)%tab_width;
6011438aefcSRuslan Ermilov     else if (ch=='\b') { if (len) --len; }
6021438aefcSRuslan Ermilov   }
6031438aefcSRuslan Ermilov   *lengthp=len;
6041438aefcSRuslan Ermilov   return (len>0 || ch!=EOF) ? buf : 0;
6059b50d902SRodney W. Grimes }
6069b50d902SRodney W. Grimes 
6071438aefcSRuslan Ermilov /* (Re)allocate some memory, exiting with an error if we can't.
6089b50d902SRodney W. Grimes  */
6091438aefcSRuslan Ermilov static void *
6101438aefcSRuslan Ermilov xrealloc(void *ptr, size_t nbytes) {
6111438aefcSRuslan Ermilov   void *p = realloc(ptr, nbytes);
6121438aefcSRuslan Ermilov   if (p == NULL) errx(EX_OSERR, "out of memory");
6131438aefcSRuslan Ermilov   return p;
6149b50d902SRodney W. Grimes }
615