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
17277807Srustatic const char copyright[] =
17377807Sru  "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n";
1741590Srgrimes#endif /* not lint */
17599112Sobrien#include <sys/cdefs.h>
17699112Sobrien__FBSDID("$FreeBSD$");
1771590Srgrimes
17827185Scharnier#include <err.h>
179172721Sjmallett#include <limits.h>
18011765Sache#include <locale.h>
18127185Scharnier#include <stdio.h>
18212317Sjoerg#include <stdlib.h>
183200462Sdelphij#include <string.h>
18477807Sru#include <sysexits.h>
18577807Sru#include <unistd.h>
186133008Stjr#include <wchar.h>
187133008Stjr#include <wctype.h>
1881590Srgrimes
18977807Sru/* Something that, we hope, will never be a genuine line length,
19077807Sru * indentation etc.
1911590Srgrimes */
19277807Sru#define SILLY ((size_t)-1)
1931590Srgrimes
19477807Sru/* I used to use |strtoul| for this, but (1) not all systems have it
19577807Sru * and (2) it's probably better to use |strtol| to detect negative
19677807Sru * numbers better.
19777807Sru * If |fussyp==0| then we don't complain about non-numbers
19877807Sru * (returning 0 instead), but we do complain about bad numbers.
1991590Srgrimes */
20077807Srustatic size_t
20177807Sruget_positive(const char *s, const char *err_mess, int fussyP) {
20277807Sru  char *t;
20377807Sru  long result = strtol(s,&t,0);
20477807Sru  if (*t) { if (fussyP) goto Lose; else return 0; }
20581510Skris  if (result<=0) { Lose: errx(EX_USAGE, "%s", err_mess); }
20677807Sru  return (size_t) result;
20777807Sru}
2081590Srgrimes
20981701Srustatic size_t
21081701Sruget_nonnegative(const char *s, const char *err_mess, int fussyP) {
21181701Sru  char *t;
21281701Sru  long result = strtol(s,&t,0);
21381701Sru  if (*t) { if (fussyP) goto Lose; else return 0; }
21481701Sru  if (result<0) { Lose: errx(EX_USAGE, "%s", err_mess); }
21581701Sru  return (size_t) result;
21681701Sru}
21781701Sru
21877807Sru/* Global variables */
2191590Srgrimes
22077807Srustatic int centerP=0;		/* Try to center lines? */
22177807Srustatic size_t goal_length=0;	/* Target length for output lines */
22277807Srustatic size_t max_length=0;	/* Maximum length for output lines */
22377807Srustatic int coalesce_spaces_P=0;	/* Coalesce multiple whitespace -> ' ' ? */
22477807Srustatic int allow_indented_paragraphs=0;	/* Can first line have diff. ind.? */
22577807Srustatic int tab_width=8;		/* Number of spaces per tab stop */
22681701Srustatic size_t output_tab_width=8;	/* Ditto, when squashing leading spaces */
227133008Stjrstatic const wchar_t *sentence_enders=L".?!";	/* Double-space after these */
22877807Srustatic int grok_mail_headers=0;	/* treat embedded mail headers magically? */
22989268Srustatic int format_troff=0;	/* Format troff? */
2301590Srgrimes
23177807Srustatic int n_errors=0;		/* Number of failed files. Return on exit. */
232133008Stjrstatic wchar_t *output_buffer=0;	/* Output line will be built here */
23377807Srustatic size_t x;		/* Horizontal position in output line */
23477807Srustatic size_t x0;		/* Ditto, ignoring leading whitespace */
235133008Stjrstatic size_t output_buffer_length = 0;
23677807Srustatic size_t pending_spaces;	/* Spaces to add before next word */
23777807Srustatic int output_in_paragraph=0;	/* Any of current para written out yet? */
23827185Scharnier
23977807Sru/* Prototypes */
24077807Sru
24177807Srustatic void process_named_file (const char *);
24277807Srustatic void     process_stream (FILE *, const char *);
243133008Stjrstatic size_t    indent_length (const wchar_t *, size_t);
244133008Stjrstatic int     might_be_header (const wchar_t *);
24577807Srustatic void      new_paragraph (size_t, size_t);
246133008Stjrstatic void        output_word (size_t, size_t, const wchar_t *, size_t,
247133008Stjr				size_t);
24877807Srustatic void      output_indent (size_t);
24977807Srustatic void      center_stream (FILE *, const char *);
250133008Stjrstatic wchar_t *      get_line (FILE *, size_t *);
25177807Srustatic void *         xrealloc (void *, size_t);
25277807Sru
25377807Sru#define XMALLOC(x) xrealloc(0,x)
25477807Sru
25577807Sru/* Here is perhaps the right place to mention that this code is
25677807Sru * all in top-down order. Hence, |main| comes first.
2571590Srgrimes */
25827185Scharnierint
25977807Srumain(int argc, char *argv[]) {
26077807Sru  int ch;			/* used for |getopt| processing */
261133008Stjr  wchar_t *tmp;
262133008Stjr  size_t len;
263133008Stjr  const char *src;
2641590Srgrimes
26577807Sru  (void) setlocale(LC_CTYPE, "");
2661590Srgrimes
26777807Sru  /* 1. Grok parameters. */
2681590Srgrimes
26989268Sru  while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1)
27077807Sru  switch(ch) {
27177807Sru    case 'c':
27277807Sru      centerP = 1;
27389268Sru      format_troff = 1;
27477807Sru      continue;
27577807Sru    case 'd':
276133008Stjr      src = optarg;
277133008Stjr      len = mbsrtowcs(NULL, &src, 0, NULL);
278133008Stjr      if (len == (size_t)-1)
279133008Stjr        err(EX_USAGE, "bad sentence-ending character set");
280133008Stjr      tmp = XMALLOC((len + 1) * sizeof(wchar_t));
281133008Stjr      mbsrtowcs(tmp, &src, len + 1, NULL);
282133008Stjr      sentence_enders = tmp;
28377807Sru      continue;
28477807Sru    case 'l':
28577807Sru      output_tab_width
28681701Sru        = get_nonnegative(optarg, "output tab width must be non-negative", 1);
28777807Sru      continue;
28877807Sru    case 'm':
28977807Sru      grok_mail_headers = 1;
29077807Sru      continue;
29189268Sru    case 'n':
29289268Sru      format_troff = 1;
29389268Sru      continue;
29477807Sru    case 'p':
29577807Sru      allow_indented_paragraphs = 1;
29677807Sru      continue;
29777807Sru    case 's':
29877807Sru      coalesce_spaces_P = 1;
29977807Sru      continue;
30077807Sru    case 't':
30177807Sru      tab_width = get_positive(optarg, "tab width must be positive", 1);
30277807Sru      continue;
30377807Sru    case 'w':
30477807Sru      goal_length = get_positive(optarg, "width must be positive", 1);
30577807Sru      max_length = goal_length;
30677807Sru      continue;
30777807Sru    case '0': case '1': case '2': case '3': case '4': case '5':
30877807Sru    case '6': case '7': case '8': case '9':
30977807Sru    /* XXX  this is not a stylistically approved use of getopt() */
31077807Sru      if (goal_length==0) {
31177807Sru        char *p;
31277807Sru        p = argv[optind - 1];
31377807Sru        if (p[0] == '-' && p[1] == ch && !p[2])
31477807Sru             goal_length = get_positive(++p, "width must be nonzero", 1);
31577807Sru        else
31677807Sru             goal_length = get_positive(argv[optind]+1,
31777807Sru                 "width must be nonzero", 1);
31877807Sru        max_length = goal_length;
31977807Sru      }
32077807Sru      continue;
32177807Sru    case 'h': default:
32277807Sru      fprintf(stderr,
32395258Sdes"usage:   fmt [-cmps] [-d chars] [-l num] [-t num]\n"
32477807Sru"             [-w width | -width | goal [maximum]] [file ...]\n"
32577807Sru"Options: -c     center each line instead of formatting\n"
32677807Sru"         -d <chars> double-space after <chars> at line end\n"
32777807Sru"         -l <n> turn each <n> spaces at start of line into a tab\n"
32877807Sru"         -m     try to make sure mail header lines stay separate\n"
32989268Sru"         -n     format lines beginning with a dot\n"
33077807Sru"         -p     allow indented paragraphs\n"
33177807Sru"         -s     coalesce whitespace inside lines\n"
33277807Sru"         -t <n> have tabs every <n> columns\n"
33377807Sru"         -w <n> set maximum width to <n>\n"
33477807Sru"         goal   set target width to goal\n");
33577807Sru      exit(ch=='h' ? 0 : EX_USAGE);
33677807Sru  }
33777807Sru  argc -= optind; argv += optind;
33828478Sjlemon
33977807Sru  /* [ goal [ maximum ] ] */
3401590Srgrimes
34177807Sru  if (argc>0 && goal_length==0
34277807Sru      && (goal_length=get_positive(*argv,"goal length must be positive", 0))
34377807Sru         != 0) {
34477807Sru    --argc; ++argv;
34577807Sru    if (argc>0
34677807Sru        && (max_length=get_positive(*argv,"max length must be positive", 0))
34777807Sru           != 0) {
34877807Sru      --argc; ++argv;
34977807Sru      if (max_length<goal_length)
35077807Sru        errx(EX_USAGE, "max length must be >= goal length");
35177807Sru    }
35277807Sru  }
35377807Sru  if (goal_length==0) goal_length = 65;
35477807Sru  if (max_length==0) max_length = goal_length+10;
355172721Sjmallett  if (max_length >= SIZE_T_MAX / sizeof (wchar_t)) errx(EX_USAGE, "max length too large");
356133008Stjr  /* really needn't be longer */
357133008Stjr  output_buffer = XMALLOC((max_length+1) * sizeof(wchar_t));
3588874Srgrimes
35977807Sru  /* 2. Process files. */
36015344Ssmpatel
36177807Sru  if (argc>0) {
36277807Sru    while (argc-->0) process_named_file(*argv++);
36377807Sru  }
36477807Sru  else {
36577807Sru    process_stream(stdin, "standard input");
36677807Sru  }
3671590Srgrimes
36877807Sru  /* We're done. */
36977807Sru
37077807Sru  return n_errors ? EX_NOINPUT : 0;
37177807Sru
3721590Srgrimes}
3731590Srgrimes
37477807Sru/* Process a single file, given its name.
3751590Srgrimes */
37677807Srustatic void
37777807Sruprocess_named_file(const char *name) {
37877807Sru  FILE *f=fopen(name, "r");
379132178Stjr  if (!f) { warn("%s", name); ++n_errors; }
38077807Sru  else {
38177807Sru    process_stream(f, name);
382133008Stjr    if (ferror(f)) { warn("%s", name); ++n_errors; }
38377807Sru    fclose(f);
38477807Sru  }
3851590Srgrimes}
3861590Srgrimes
38777807Sru/* Types of mail header continuation lines:
3881590Srgrimes */
38977807Srutypedef enum {
39077807Sru  hdr_ParagraphStart = -1,
39177807Sru  hdr_NonHeader      = 0,
39277807Sru  hdr_Header         = 1,
39377807Sru  hdr_Continuation   = 2
39477807Sru} HdrType;
3951590Srgrimes
39677807Sru/* Process a stream. This is where the real work happens,
39777807Sru * except that centering is handled separately.
39877807Sru */
39977807Srustatic void
40077807Sruprocess_stream(FILE *stream, const char *name) {
40177807Sru  size_t last_indent=SILLY;	/* how many spaces in last indent? */
40277807Sru  size_t para_line_number=0;	/* how many lines already read in this para? */
40377807Sru  size_t first_indent=SILLY;	/* indentation of line 0 of paragraph */
40477807Sru  HdrType prev_header_type=hdr_ParagraphStart;
40577807Sru	/* ^-- header_type of previous line; -1 at para start */
406133008Stjr  wchar_t *line;
40777807Sru  size_t length;
40830009Sjoerg
40977807Sru  if (centerP) { center_stream(stream, name); return; }
41077807Sru  while ((line=get_line(stream,&length)) != NULL) {
41177807Sru    size_t np=indent_length(line, length);
41277807Sru    { HdrType header_type=hdr_NonHeader;
41377807Sru      if (grok_mail_headers && prev_header_type!=hdr_NonHeader) {
41477807Sru        if (np==0 && might_be_header(line))
41577807Sru          header_type = hdr_Header;
41677807Sru        else if (np>0 && prev_header_type>hdr_NonHeader)
41777807Sru          header_type = hdr_Continuation;
41877807Sru      }
41977807Sru      /* We need a new paragraph if and only if:
42077807Sru       *   this line is blank,
42189268Sru       *   OR it's a troff request (and we don't format troff),
42277807Sru       *   OR it's a mail header,
42377807Sru       *   OR it's not a mail header AND the last line was one,
42477807Sru       *   OR the indentation has changed
42577807Sru       *      AND the line isn't a mail header continuation line
42677807Sru       *      AND this isn't the second line of an indented paragraph.
42777807Sru       */
42877807Sru      if ( length==0
42989268Sru           || (line[0]=='.' && !format_troff)
43077807Sru           || header_type==hdr_Header
43177807Sru           || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader)
43277807Sru           || (np!=last_indent
43377807Sru               && header_type != hdr_Continuation
43477807Sru               && (!allow_indented_paragraphs || para_line_number != 1)) ) {
43577807Sru        new_paragraph(output_in_paragraph ? last_indent : first_indent, np);
43677807Sru        para_line_number = 0;
43777807Sru        first_indent = np;
43877807Sru        last_indent = np;
43977807Sru        if (header_type==hdr_Header) last_indent=2;	/* for cont. lines */
44089268Sru        if (length==0 || (line[0]=='.' && !format_troff)) {
44189268Sru          if (length==0)
442133008Stjr            putwchar('\n');
44389268Sru          else
444133008Stjr            wprintf(L"%.*ls\n", (int)length, line);
44577807Sru          prev_header_type=hdr_ParagraphStart;
44677807Sru          continue;
44777807Sru        }
44877807Sru      }
44977807Sru      else {
45077807Sru        /* If this is an indented paragraph other than a mail header
45177807Sru         * continuation, set |last_indent|.
45277807Sru         */
45377807Sru        if (np != last_indent && header_type != hdr_Continuation)
45477807Sru          last_indent=np;
45577807Sru      }
45677807Sru      prev_header_type = header_type;
45777807Sru    }
4581590Srgrimes
45977807Sru    { size_t n=np;
46077807Sru      while (n<length) {
46177807Sru        /* Find word end and count spaces after it */
46277807Sru        size_t word_length=0, space_length=0;
46377807Sru        while (n+word_length < length && line[n+word_length] != ' ')
46477807Sru          ++word_length;
46577807Sru        space_length = word_length;
46677807Sru        while (n+space_length < length && line[n+space_length] == ' ')
46777807Sru          ++space_length;
46877807Sru        /* Send the word to the output machinery. */
46977807Sru        output_word(first_indent, last_indent,
47077807Sru                    line+n, word_length, space_length-word_length);
47177807Sru        n += space_length;
47277807Sru      }
47377807Sru    }
47477807Sru    ++para_line_number;
47577807Sru  }
47677807Sru  new_paragraph(output_in_paragraph ? last_indent : first_indent, 0);
477132178Stjr  if (ferror(stream)) { warn("%s", name); ++n_errors; }
4781590Srgrimes}
4791590Srgrimes
48077807Sru/* How long is the indent on this line?
4811590Srgrimes */
48277807Srustatic size_t
483133008Stjrindent_length(const wchar_t *line, size_t length) {
48477807Sru  size_t n=0;
48577807Sru  while (n<length && *line++ == ' ') ++n;
48677807Sru  return n;
48777807Sru}
4881590Srgrimes
48977807Sru/* Might this line be a mail header?
49077807Sru * We deem a line to be a possible header if it matches the
49177807Sru * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same
49277807Sru * as in RFC whatever-number-it-is; we want to be gratuitously
49377807Sru * conservative to avoid mangling ordinary civilised text.
4941590Srgrimes */
49577807Srustatic int
496133008Stjrmight_be_header(const wchar_t *line) {
497133008Stjr  if (!iswupper(*line++)) return 0;
498133008Stjr  while (*line && (iswalnum(*line) || *line=='-')) ++line;
499133008Stjr  return (*line==':' && iswspace(line[1]));
5001590Srgrimes}
5011590Srgrimes
50277807Sru/* Begin a new paragraph with an indent of |indent| spaces.
5031590Srgrimes */
50477807Srustatic void
50577807Srunew_paragraph(size_t old_indent, size_t indent) {
506133008Stjr  if (output_buffer_length) {
50777807Sru    if (old_indent>0) output_indent(old_indent);
508133008Stjr    wprintf(L"%.*ls\n", (int)output_buffer_length, output_buffer);
50977807Sru  }
510133008Stjr  x=indent; x0=0; output_buffer_length=0; pending_spaces=0;
51177807Sru  output_in_paragraph = 0;
5121590Srgrimes}
5131590Srgrimes
51477807Sru/* Output spaces or tabs for leading indentation.
5151590Srgrimes */
51677807Srustatic void
51777807Sruoutput_indent(size_t n_spaces) {
51877807Sru  if (output_tab_width) {
51977807Sru    while (n_spaces >= output_tab_width) {
520133008Stjr      putwchar('\t');
52177807Sru      n_spaces -= output_tab_width;
52277807Sru    }
52377807Sru  }
524133008Stjr  while (n_spaces-- > 0) putwchar(' ');
5251590Srgrimes}
5261590Srgrimes
52777807Sru/* Output a single word, or add it to the buffer.
52877807Sru * indent0 and indent1 are the indents to use on the first and subsequent
52977807Sru * lines of a paragraph. They'll often be the same, of course.
5301590Srgrimes */
53177807Srustatic void
532133008Stjroutput_word(size_t indent0, size_t indent1, const wchar_t *word, size_t length, size_t spaces) {
533133008Stjr  size_t new_x;
53477807Sru  size_t indent = output_in_paragraph ? indent1 : indent0;
535133008Stjr  size_t width;
536133008Stjr  const wchar_t *p;
537133008Stjr  int cwidth;
5381590Srgrimes
539133008Stjr  for (p = word, width = 0; p < &word[length]; p++)
540133008Stjr    width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1;
541133008Stjr
542133008Stjr  new_x = x + pending_spaces + width;
543133008Stjr
54477807Sru  /* If either |spaces==0| (at end of line) or |coalesce_spaces_P|
54577807Sru   * (squashing internal whitespace), then add just one space;
54677807Sru   * except that if the last character was a sentence-ender we
54777807Sru   * actually add two spaces.
54877807Sru   */
54977807Sru  if (coalesce_spaces_P || spaces==0)
550133008Stjr    spaces = wcschr(sentence_enders, word[length-1]) ? 2 : 1;
5518874Srgrimes
55277807Sru  if (new_x<=goal_length) {
55377807Sru    /* After adding the word we still aren't at the goal length,
55477807Sru     * so clearly we add it to the buffer rather than outputing it.
55577807Sru     */
556133008Stjr    wmemset(output_buffer+output_buffer_length, L' ', pending_spaces);
55777807Sru    x0 += pending_spaces; x += pending_spaces;
558133008Stjr    output_buffer_length += pending_spaces;
559133008Stjr    wmemcpy(output_buffer+output_buffer_length, word, length);
560133008Stjr    x0 += width; x += width; output_buffer_length += length;
56177807Sru    pending_spaces = spaces;
56277807Sru  }
56377807Sru  else {
56477807Sru    /* Adding the word takes us past the goal. Print the line-so-far,
56577807Sru     * and the word too iff either (1) the lsf is empty or (2) that
56677807Sru     * makes us nearer the goal but doesn't take us over the limit,
56777807Sru     * or (3) the word on its own takes us over the limit.
56877807Sru     * In case (3) we put a newline in between.
56977807Sru     */
57077807Sru    if (indent>0) output_indent(indent);
571133008Stjr    wprintf(L"%.*ls", (int)output_buffer_length, output_buffer);
57277807Sru    if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) {
573133008Stjr      wprintf(L"%*ls", (int)pending_spaces, L"");
57477807Sru      goto write_out_word;
57577807Sru    }
57677807Sru    else {
57777807Sru      /* If the word takes us over the limit on its own, just
57877807Sru       * spit it out and don't bother buffering it.
57977807Sru       */
580133008Stjr      if (indent+width > max_length) {
581133008Stjr        putwchar('\n');
58277807Sru        if (indent>0) output_indent(indent);
58377807Sruwrite_out_word:
584133008Stjr        wprintf(L"%.*ls", (int)length, word);
58577807Sru        x0 = 0; x = indent1; pending_spaces = 0;
586133008Stjr        output_buffer_length = 0;
58777807Sru      }
58877807Sru      else {
589133008Stjr        wmemcpy(output_buffer, word, length);
590133008Stjr        x0 = width; x = width+indent1; pending_spaces = spaces;
591133008Stjr        output_buffer_length = length;
59277807Sru      }
59377807Sru    }
594133008Stjr    putwchar('\n');
59577807Sru    output_in_paragraph = 1;
59677807Sru  }
5971590Srgrimes}
5981590Srgrimes
59977807Sru/* Process a stream, but just center its lines rather than trying to
60077807Sru * format them neatly.
6011590Srgrimes */
60277807Srustatic void
60377807Srucenter_stream(FILE *stream, const char *name) {
604133008Stjr  wchar_t *line, *p;
60577807Sru  size_t length;
606133008Stjr  size_t width;
607133008Stjr  int cwidth;
60877807Sru  while ((line=get_line(stream, &length)) != 0) {
60977807Sru    size_t l=length;
610133008Stjr    while (l>0 && iswspace(*line)) { ++line; --l; }
61177807Sru    length=l;
612133008Stjr    for (p = line, width = 0; p < &line[length]; p++)
613133008Stjr      width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1;
614133008Stjr    l = width;
615133008Stjr    while (l<goal_length) { putwchar(' '); l+=2; }
616133008Stjr    wprintf(L"%.*ls\n", (int)length, line);
61777807Sru  }
618132178Stjr  if (ferror(stream)) { warn("%s", name); ++n_errors; }
6191590Srgrimes}
6201590Srgrimes
62177807Sru/* Get a single line from a stream. Expand tabs, strip control
62277807Sru * characters and trailing whitespace, and handle backspaces.
62377807Sru * Return the address of the buffer containing the line, and
62477807Sru * put the length of the line in |lengthp|.
62577807Sru * This can cope with arbitrarily long lines, and with lines
62677807Sru * without terminating \n.
62777807Sru * If there are no characters left or an error happens, we
62877807Sru * return 0.
62977807Sru * Don't confuse |spaces_pending| here with the global
63077807Sru * |pending_spaces|.
6311590Srgrimes */
632133008Stjrstatic wchar_t *
63377807Sruget_line(FILE *stream, size_t *lengthp) {
634133008Stjr  static wchar_t *buf=NULL;
63577807Sru  static size_t length=0;
63677807Sru  size_t len=0;
637133008Stjr  wint_t ch;
63877807Sru  size_t spaces_pending=0;
63989268Sru  int troff=0;
640133008Stjr  size_t col=0;
641133008Stjr  int cwidth;
6421590Srgrimes
643133008Stjr  if (buf==NULL) { length=100; buf=XMALLOC(length * sizeof(wchar_t)); }
644133008Stjr  while ((ch=getwc(stream)) != '\n' && ch != WEOF) {
64589268Sru    if (len+spaces_pending==0 && ch=='.' && !format_troff) troff=1;
64677807Sru    if (ch==' ') ++spaces_pending;
647133008Stjr    else if (troff || iswprint(ch)) {
64877807Sru      while (len+spaces_pending >= length) {
649133008Stjr        length*=2; buf=xrealloc(buf, length * sizeof(wchar_t));
65077807Sru      }
651133008Stjr      while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; col++; }
65277807Sru      buf[len++] = ch;
653133008Stjr      col += (cwidth = wcwidth(ch)) > 0 ? cwidth : 1;
65477807Sru    }
65577807Sru    else if (ch=='\t')
656133008Stjr      spaces_pending += tab_width - (col+spaces_pending)%tab_width;
657133008Stjr    else if (ch=='\b') { if (len) --len; if (col) --col; }
65877807Sru  }
65977807Sru  *lengthp=len;
660133008Stjr  return (len>0 || ch!=WEOF) ? buf : 0;
6611590Srgrimes}
6621590Srgrimes
66377807Sru/* (Re)allocate some memory, exiting with an error if we can't.
6641590Srgrimes */
66577807Srustatic void *
66677807Sruxrealloc(void *ptr, size_t nbytes) {
66777807Sru  void *p = realloc(ptr, nbytes);
66877807Sru  if (p == NULL) errx(EX_OSERR, "out of memory");
66977807Sru  return p;
6701590Srgrimes}
671