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