1/*	$OpenBSD: fmt.c,v 1.16 2000/06/25 15:35:42 pjanzen 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 * $FreeBSD: src/usr.bin/fmt/fmt.c,v 1.12.2.2 2002/01/14 09:48:26 ru Exp $
126 */
127
128/* Copyright (c) 1997 Gareth McCaughan. All rights reserved.
129 *
130 * Redistribution and use of this code, in source or binary forms,
131 * with or without modification, are permitted subject to the following
132 * conditions:
133 *
134 *  - Redistribution of source code must retain the above copyright
135 *    notice, this list of conditions and the following disclaimer.
136 *
137 *  - If you distribute modified source code it must also include
138 *    a notice saying that it has been modified, and giving a brief
139 *    description of what changes have been made.
140 *
141 * Disclaimer: I am not responsible for the results of using this code.
142 *             If it formats your hard disc, sends obscene messages to
143 *             your boss and kills your children then that's your problem
144 *             not mine. I give absolutely no warranty of any sort as to
145 *             what the program will do, and absolutely refuse to be held
146 *             liable for any consequences of your using it.
147 *             Thank you. Have a nice day.
148 */
149
150/* RCS change log:
151 * Revision 1.5  1998/03/02 18:02:21  gjm11
152 * Minor changes for portability.
153 *
154 * Revision 1.4  1997/10/01 11:51:28  gjm11
155 * Repair broken indented-paragraph handling.
156 * Add mail message header stuff.
157 * Improve comments and layout.
158 * Make usable with non-BSD systems.
159 * Add revision display to usage message.
160 *
161 * Revision 1.3  1997/09/30 16:24:47  gjm11
162 * Add copyright notice, rcsid string and log message.
163 *
164 * Revision 1.2  1997/09/30 16:13:39  gjm11
165 * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h .
166 * Parse options with `getopt'. Clean up code generally.
167 * Make comments more accurate.
168 *
169 * Revision 1.1  1997/09/30 11:29:57  gjm11
170 * Initial revision
171 */
172
173#include <ctype.h>
174#include <err.h>
175#include <locale.h>
176#include <stdio.h>
177#include <stdlib.h>
178#include <string.h>
179#include <sysexits.h>
180#include <unistd.h>
181
182/* Something that, we hope, will never be a genuine line length,
183 * indentation etc.
184 */
185#define SILLY ((size_t)-1)
186
187/* I used to use |strtoul| for this, but (1) not all systems have it
188 * and (2) it's probably better to use |strtol| to detect negative
189 * numbers better.
190 * If |fussyp==0| then we don't complain about non-numbers
191 * (returning 0 instead), but we do complain about bad numbers.
192 */
193static size_t
194get_positive(const char *s, const char *err_mess, int fussyP) {
195  char *t;
196  long result = strtol(s,&t,0);
197  if (*t) { if (fussyP) goto Lose; else return 0; }
198  if (result<=0) { Lose: errx(EX_USAGE, "%s", err_mess); }
199  return (size_t) result;
200}
201
202static size_t
203get_nonnegative(const char *s, const char *err_mess, int fussyP) {
204  char *t;
205  long result = strtol(s,&t,0);
206  if (*t) { if (fussyP) goto Lose; else return 0; }
207  if (result<0) { Lose: errx(EX_USAGE, "%s", err_mess); }
208  return (size_t) result;
209}
210
211/* Global variables */
212
213static int centerP=0;		/* Try to center lines? */
214static size_t goal_length=0;	/* Target length for output lines */
215static size_t max_length=0;	/* Maximum length for output lines */
216static int coalesce_spaces_P=0;	/* Coalesce multiple whitespace -> ' ' ? */
217static int allow_indented_paragraphs=0;	/* Can first line have diff. ind.? */
218static int tab_width=8;		/* Number of spaces per tab stop */
219static size_t output_tab_width=8;	/* Ditto, when squashing leading spaces */
220static const char *sentence_enders=".?!";	/* Double-space after these */
221static int grok_mail_headers=0;	/* treat embedded mail headers magically? */
222static int format_troff=0;	/* Format troff? */
223
224static int n_errors=0;		/* Number of failed files. Return on exit. */
225static char *output_buffer=NULL;	/* Output line will be built here */
226static size_t x;		/* Horizontal position in output line */
227static size_t x0;		/* Ditto, ignoring leading whitespace */
228static size_t pending_spaces;	/* Spaces to add before next word */
229static int output_in_paragraph=0;	/* Any of current para written out yet? */
230
231/* Prototypes */
232
233static void process_named_file (const char *);
234static void     process_stream (FILE *, const char *);
235static size_t    indent_length (const char *, size_t);
236static int     might_be_header (const unsigned char *);
237static void      new_paragraph (size_t, size_t);
238static void        output_word (size_t, size_t, const char *, size_t, size_t);
239static void      output_indent (size_t);
240static void      center_stream (FILE *, const char *);
241static char *         get_line (FILE *, size_t *);
242static void *         xrealloc (void *, size_t);
243
244#define XMALLOC(x) xrealloc(0,x)
245
246/* Here is perhaps the right place to mention that this code is
247 * all in top-down order. Hence, |main| comes first.
248 */
249int
250main(int argc, char *argv[]) {
251  int ch;			/* used for |getopt| processing */
252
253
254  (void) setlocale(LC_CTYPE, "");
255
256  /* 1. Grok parameters. */
257
258  while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1)
259    switch(ch) {
260    case 'c':
261      centerP = 1;
262      format_troff = 1;
263      continue;
264    case 'd':
265      sentence_enders = optarg;
266      continue;
267    case 'l':
268      output_tab_width
269        = get_nonnegative(optarg, "output tab width must be non-negative", 1);
270      continue;
271    case 'm':
272      grok_mail_headers = 1;
273      continue;
274    case 'n':
275      format_troff = 1;
276      continue;
277    case 'p':
278      allow_indented_paragraphs = 1;
279      continue;
280    case 's':
281      coalesce_spaces_P = 1;
282      continue;
283    case 't':
284      tab_width = get_positive(optarg, "tab width must be positive", 1);
285      continue;
286    case 'w':
287      goal_length = get_positive(optarg, "width must be positive", 1);
288      max_length = goal_length;
289      continue;
290    case '0': case '1': case '2': case '3': case '4': case '5':
291    case '6': case '7': case '8': case '9':
292    /* XXX  this is not a stylistically approved use of getopt() */
293      if (goal_length==0) {
294        char *p;
295        p = argv[optind - 1];
296        if (p[0] == '-' && p[1] == ch && !p[2])
297             goal_length = get_positive(++p, "width must be nonzero", 1);
298        else
299             goal_length = get_positive(argv[optind]+1,
300                 "width must be nonzero", 1);
301        max_length = goal_length;
302      }
303      continue;
304    case 'h': default:
305      fprintf(stderr,
306"Usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
307"             [-w width | -width | goal [maximum]] [file ...]\n"
308"Options: -c     center each line instead of formatting\n"
309"         -d <chars> double-space after <chars> at line end\n"
310"         -l <n> turn each <n> spaces at start of line into a tab\n"
311"         -m     try to make sure mail header lines stay separate\n"
312"         -n     format lines beginning with a dot\n"
313"         -p     allow indented paragraphs\n"
314"         -s     coalesce whitespace inside lines\n"
315"         -t <n> have tabs every <n> columns\n"
316"         -w <n> set maximum width to <n>\n"
317"         goal   set target width to goal\n");
318      exit(ch=='h' ? 0 : EX_USAGE);
319    }
320  argc -= optind; argv += optind;
321
322  /* [ goal [ maximum ] ] */
323
324  if (argc>0 && goal_length==0
325      && (goal_length=get_positive(*argv,"goal length must be positive", 0))
326         != 0) {
327    --argc; ++argv;
328    if (argc>0
329        && (max_length=get_positive(*argv,"max length must be positive", 0))
330           != 0) {
331      --argc; ++argv;
332      if (max_length<goal_length)
333        errx(EX_USAGE, "max length must be >= goal length");
334    }
335  }
336  if (goal_length==0) goal_length = 65;
337  if (max_length==0) max_length = goal_length+10;
338  output_buffer = XMALLOC(max_length+1);	/* really needn't be longer */
339
340  /* 2. Process files. */
341
342  if (argc>0) {
343    while (argc-->0) process_named_file(*argv++);
344  }
345  else {
346    process_stream(stdin, "standard input");
347  }
348
349  /* We're done. */
350
351  return n_errors ? EX_NOINPUT : 0;
352
353}
354
355/* Process a single file, given its name.
356 */
357static void
358process_named_file(const char *name) {
359  FILE *f=fopen(name, "r");
360  if (!f) { perror(name); ++n_errors; }
361  else {
362    process_stream(f, name);
363    fclose(f);
364  }
365}
366
367/* Types of mail header continuation lines:
368 */
369typedef enum {
370  hdr_ParagraphStart = -1,
371  hdr_NonHeader      = 0,
372  hdr_Header         = 1,
373  hdr_Continuation   = 2
374} HdrType;
375
376/* Process a stream. This is where the real work happens,
377 * except that centering is handled separately.
378 */
379static void
380process_stream(FILE *stream, const char *name) {
381  size_t last_indent=SILLY;	/* how many spaces in last indent? */
382  size_t para_line_number=0;	/* how many lines already read in this para? */
383  size_t first_indent=SILLY;	/* indentation of line 0 of paragraph */
384  HdrType prev_header_type=hdr_ParagraphStart;
385	/* ^-- header_type of previous line; -1 at para start */
386  char *line;
387  size_t length;
388
389  if (centerP) { center_stream(stream, name); return; }
390  while ((line=get_line(stream,&length)) != NULL) {
391    size_t np=indent_length(line, length);
392    { HdrType header_type=hdr_NonHeader;
393      if (grok_mail_headers && prev_header_type!=hdr_NonHeader) {
394        if (np==0 && might_be_header(line))
395          header_type = hdr_Header;
396        else if (np>0 && prev_header_type>hdr_NonHeader)
397          header_type = hdr_Continuation;
398      }
399      /* We need a new paragraph if and only if:
400       *   this line is blank,
401       *   OR it's a troff request (and we don't format troff),
402       *   OR it's a mail header,
403       *   OR it's not a mail header AND the last line was one,
404       *   OR the indentation has changed
405       *      AND the line isn't a mail header continuation line
406       *      AND this isn't the second line of an indented paragraph.
407       */
408      if ( length==0
409           || (line[0]=='.' && !format_troff)
410           || header_type==hdr_Header
411           || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader)
412           || (np!=last_indent
413               && header_type != hdr_Continuation
414               && (!allow_indented_paragraphs || para_line_number != 1)) ) {
415        new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
416        para_line_number = 0;
417        first_indent = np;
418        last_indent = np;
419        if (header_type==hdr_Header) last_indent=2;	/* for cont. lines */
420        if (length==0 || (line[0]=='.' && !format_troff)) {
421          if (length==0)
422            putchar('\n');
423          else
424            printf("%.*s\n", (int)length, line);
425          prev_header_type=hdr_ParagraphStart;
426          continue;
427        }
428      }
429      else {
430        /* If this is an indented paragraph other than a mail header
431         * continuation, set |last_indent|.
432         */
433        if (np != last_indent && header_type != hdr_Continuation)
434          last_indent=np;
435      }
436      prev_header_type = header_type;
437    }
438
439    { size_t n=np;
440      while (n<length) {
441        /* Find word end and count spaces after it */
442        size_t word_length=0, space_length=0;
443        while (n+word_length < length && line[n+word_length] != ' ')
444          ++word_length;
445        space_length = word_length;
446        while (n+space_length < length && line[n+space_length] == ' ')
447          ++space_length;
448        /* Send the word to the output machinery. */
449        output_word(first_indent, last_indent,
450                    line+n, word_length, space_length-word_length);
451        n += space_length;
452      }
453    }
454    ++para_line_number;
455  }
456  new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
457  if (ferror(stream)) { perror(name); ++n_errors; }
458}
459
460/* How long is the indent on this line?
461 */
462static size_t
463indent_length(const char *line, size_t length) {
464  size_t n=0;
465  while (n<length && *line++ == ' ') ++n;
466  return n;
467}
468
469/* Might this line be a mail header?
470 * We deem a line to be a possible header if it matches the
471 * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
472 * as in RFC whatever-number-it-is; we want to be gratuitously
473 * conservative to avoid mangling ordinary civilised text.
474 */
475static int
476might_be_header(const unsigned char *line) {
477  if (!isupper(*line++)) return 0;
478  while (*line && (isalnum(*line) || *line=='-')) ++line;
479  return (*line==':' && isspace(line[1]));
480}
481
482/* Begin a new paragraph with an indent of |indent| spaces.
483 */
484static void
485new_paragraph(size_t old_indent, size_t indent) {
486  if (x0) {
487    if (old_indent>0) output_indent(old_indent);
488    fwrite(output_buffer, 1, x0, stdout);
489    putchar('\n');
490  }
491  x=indent; x0=0; pending_spaces=0;
492  output_in_paragraph = 0;
493}
494
495/* Output spaces or tabs for leading indentation.
496 */
497static void
498output_indent(size_t n_spaces) {
499  if (output_tab_width) {
500    while (n_spaces >= output_tab_width) {
501      putchar('\t');
502      n_spaces -= output_tab_width;
503    }
504  }
505  while (n_spaces-- > 0) putchar(' ');
506}
507
508/* Output a single word, or add it to the buffer.
509 * indent0 and indent1 are the indents to use on the first and subsequent
510 * lines of a paragraph. They'll often be the same, of course.
511 */
512static void
513output_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces) {
514  size_t new_x = x+pending_spaces+length;
515  size_t indent = output_in_paragraph ? indent1 : indent0;
516
517  /* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
518   * (squashing internal whitespace), then add just one space;
519   * except that if the last character was a sentence-ender we
520   * actually add two spaces.
521   */
522  if (coalesce_spaces_P || spaces==0)
523    spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1;
524
525  if (new_x<=goal_length) {
526    /* After adding the word we still aren't at the goal length,
527     * so clearly we add it to the buffer rather than outputing it.
528     */
529    memset(output_buffer+x0, ' ', pending_spaces);
530    x0 += pending_spaces; x += pending_spaces;
531    memcpy(output_buffer+x0, word, length);
532    x0 += length; x += length;
533    pending_spaces = spaces;
534  }
535  else {
536    /* Adding the word takes us past the goal. Print the line-so-far,
537     * and the word too iff either (1) the lsf is empty or (2) that
538     * makes us nearer the goal but doesn't take us over the limit,
539     * or (3) the word on its own takes us over the limit.
540     * In case (3) we put a newline in between.
541     */
542    if (indent>0) output_indent(indent);
543    fwrite(output_buffer, 1, x0, stdout);
544    if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) {
545      printf("%*s", (int)pending_spaces, "");
546      goto write_out_word;
547    }
548    else {
549      /* If the word takes us over the limit on its own, just
550       * spit it out and don't bother buffering it.
551       */
552      if (indent+length > max_length) {
553        putchar('\n');
554        if (indent>0) output_indent(indent);
555write_out_word:
556        fwrite(word, 1, length, stdout);
557        x0 = 0; x = indent1; pending_spaces = 0;
558      }
559      else {
560        memcpy(output_buffer, word, length);
561        x0 = length; x = length+indent1; pending_spaces = spaces;
562      }
563    }
564    putchar('\n');
565    output_in_paragraph = 1;
566  }
567}
568
569/* Process a stream, but just center its lines rather than trying to
570 * format them neatly.
571 */
572static void
573center_stream(FILE *stream, const char *name) {
574  char *line;
575  size_t length;
576  while ((line=get_line(stream, &length)) != NULL) {
577    size_t l=length;
578    while (l>0 && isspace(*line)) { ++line; --l; }
579    length=l;
580    while (l<goal_length) { putchar(' '); l+=2; }
581    fwrite(line, 1, length, stdout);
582    putchar('\n');
583  }
584  if (ferror(stream)) { perror(name); ++n_errors; }
585}
586
587/* Get a single line from a stream. Expand tabs, strip control
588 * characters and trailing whitespace, and handle backspaces.
589 * Return the address of the buffer containing the line, and
590 * put the length of the line in |lengthp|.
591 * This can cope with arbitrarily long lines, and with lines
592 * without terminating \n.
593 * If there are no characters left or an error happens, we
594 * return 0.
595 * Don't confuse |spaces_pending| here with the global
596 * |pending_spaces|.
597 */
598static char *
599get_line(FILE *stream, size_t *lengthp) {
600  static char *buf=NULL;
601  static size_t length=0;
602  size_t len=0;
603  int ch;
604  size_t spaces_pending=0;
605  int troff=0;
606
607  if (buf==NULL) { length=100; buf=XMALLOC(length); }
608  while ((ch=getc(stream)) != '\n' && ch != EOF) {
609    if (len+spaces_pending==0 && ch=='.' && !format_troff) troff=1;
610    if (ch==' ') ++spaces_pending;
611    else if (troff || isprint(ch)) {
612      while (len+spaces_pending >= length) {
613        length*=2; buf=xrealloc(buf, length);
614      }
615      while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; }
616      buf[len++] = ch;
617    }
618    else if (ch=='\t')
619      spaces_pending += tab_width - (len+spaces_pending)%tab_width;
620    else if (ch=='\b') { if (len) --len; }
621  }
622  *lengthp=len;
623  return (len>0 || ch!=EOF) ? buf : 0;
624}
625
626/* (Re)allocate some memory, exiting with an error if we can't.
627 */
628static void *
629xrealloc(void *ptr, size_t nbytes) {
630  void *p = realloc(ptr, nbytes);
631  if (p == NULL) errx(EX_OSERR, "out of memory");
632  return p;
633}
634