home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 11 Util / 11-Util.zip / txtut122.zip / textutil / src / fmt.c < prev    next >
C/C++ Source or Header  |  1998-04-11  |  27KB  |  972 lines

  1. /* GNU fmt -- simple text formatter.
  2.    Copyright (C) 94, 95, 1996 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software Foundation,
  16.    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
  17.  
  18. /* Written by Ross Paterson <rap@doc.ic.ac.uk>.  */
  19.  
  20. #include <config.h>
  21. #include <stdio.h>
  22. #include <sys/types.h>
  23. #include <getopt.h>
  24.  
  25. #if HAVE_LIMITS_H
  26. # include <limits.h>
  27. #endif
  28.  
  29. #ifndef UINT_MAX
  30. # define UINT_MAX ((unsigned int) ~(unsigned int) 0)
  31. #endif
  32.  
  33. #ifndef INT_MAX
  34. # define INT_MAX ((int) (UINT_MAX >> 1))
  35. #endif
  36.  
  37. /* Redefine.  Otherwise, systems (Unicos for one) with headers that define
  38.    it to be a type get syntax errors for the variable declaration below.  */
  39. #define word unused_word_type
  40.  
  41. #include "system.h"
  42. #include "error.h"
  43. #include "xstrtol.h"
  44.  
  45. /* The following parameters represent the program's idea of what is
  46.    "best".  Adjust to taste, subject to the caveats given.  */
  47.  
  48. /* Default longest permitted line length (max_width).  */
  49. #define    WIDTH    75
  50.  
  51. /* Prefer lines to be LEEWAY % shorter than the maximum width, giving
  52.    room for optimization.  */
  53. #define    LEEWAY    7
  54.  
  55. /* The default secondary indent of tagged paragraph used for unindented
  56.    one-line paragraphs not preceded by any multi-line paragraphs.  */
  57. #define    DEF_INDENT 3
  58.  
  59. /* Costs and bonuses are expressed as the equivalent departure from the
  60.    optimal line length, multiplied by 10.  e.g. assigning something a
  61.    cost of 50 means that it is as bad as a line 5 characters too short
  62.    or too long.  The definition of SHORT_COST(n) should not be changed.
  63.    However, EQUIV(n) may need tuning.  */
  64.  
  65. typedef long COST;
  66.  
  67. #define    MAXCOST    (~(((unsigned long) 1) << (8 * sizeof (COST) -1)))
  68.  
  69. #define    SQR(n)        ((n) * (n))
  70. #define    EQUIV(n)    SQR ((COST) (n))
  71.  
  72. /* Cost of a filled line n chars longer or shorter than best_width.  */
  73. #define    SHORT_COST(n)    EQUIV ((n) * 10)
  74.  
  75. /* Cost of the difference between adjacent filled lines.  */
  76. #define    RAGGED_COST(n)    (SHORT_COST (n) / 2)
  77.  
  78. /* Basic cost per line.  */
  79. #define    LINE_COST    EQUIV (70)
  80.  
  81. /* Cost of breaking a line after the first word of a sentence, where
  82.    the length of the word is N.  */
  83. #define    WIDOW_COST(n)    (EQUIV (200) / ((n) + 2))
  84.  
  85. /* Cost of breaking a line before the last word of a sentence, where
  86.    the length of the word is N.  */
  87. #define    ORPHAN_COST(n)    (EQUIV (150) / ((n) + 2))
  88.  
  89. /* Bonus for breaking a line at the end of a sentence.  */
  90. #define    SENTENCE_BONUS    EQUIV (50)
  91.  
  92. /* Cost of breaking a line after a period not marking end of a sentence.
  93.    With the definition of sentence we are using (borrowed from emacs, see
  94.    get_line()) such a break would then look like a sentence break.  Hence
  95.    we assign a very high cost -- it should be avoided unless things are
  96.    really bad.  */
  97. #define    NOBREAK_COST    EQUIV (600)
  98.  
  99. /* Bonus for breaking a line before open parenthesis.  */
  100. #define    PAREN_BONUS    EQUIV (40)
  101.  
  102. /* Bonus for breaking a line after other punctuation.  */
  103. #define    PUNCT_BONUS    EQUIV(40)
  104.  
  105. /* Credit for breaking a long paragraph one line later.  */
  106. #define    LINE_CREDIT    EQUIV(3)
  107.  
  108. /* Size of paragraph buffer, in words and characters.  Longer paragraphs
  109.    are handled neatly (cf. flush_paragraph()), so there's little to gain
  110.    by making these larger.  */
  111. #define    MAXWORDS    1000
  112. #define    MAXCHARS    5000
  113.  
  114. /* Extra ctype(3)-style macros.  */
  115.  
  116. #define    isopen(c)    (strchr ("([`'\"", c) != NULL)
  117. #define    isclose(c)    (strchr (")]'\"", c) != NULL)
  118. #define    isperiod(c)    (strchr (".?!", c) != NULL)
  119.  
  120. /* Size of a tab stop, for expansion on input and re-introduction on
  121.    output.  */
  122. #define    TABWIDTH    8
  123.  
  124. /* Miscellaneous definitions.  */
  125.  
  126. typedef unsigned int bool;
  127. #undef TRUE
  128. #define TRUE    1
  129. #undef FALSE
  130. #define FALSE    0
  131.  
  132. /* Word descriptor structure.  */
  133.  
  134. typedef struct Word WORD;
  135.  
  136. struct Word
  137.   {
  138.  
  139.     /* Static attributes determined during input.  */
  140.  
  141.     const char *text;        /* the text of the word */
  142.     short length;        /* length of this word */
  143.     short space;        /* the size of the following space */
  144.     bool paren:1;        /* starts with open paren */
  145.     bool period:1;        /* ends in [.?!])* */
  146.     bool punct:1;        /* ends in punctuation */
  147.     bool final:1;        /* end of sentence */
  148.  
  149.     /* The remaining fields are computed during the optimization.  */
  150.  
  151.     short line_length;        /* length of the best line starting here */
  152.     COST best_cost;        /* cost of best paragraph starting here */
  153.     WORD *next_break;        /* break which achieves best_cost */
  154.   };
  155.  
  156. /* Forward declarations.  */
  157.  
  158. static void set_prefix __P ((char *p));
  159. static void fmt __P ((FILE *f));
  160. static bool get_paragraph __P ((FILE *f));
  161. static int get_line __P ((FILE *f, int c));
  162. static int get_prefix __P ((FILE *f));
  163. static int get_space __P ((FILE *f, int c));
  164. static int copy_rest __P ((FILE *f, int c));
  165. static bool same_para __P ((int c));
  166. static void flush_paragraph __P ((void));
  167. static void fmt_paragraph __P ((void));
  168. static void check_punctuation __P ((WORD *w));
  169. static COST base_cost __P ((WORD *this));
  170. static COST line_cost __P ((WORD *next, int len));
  171. static void put_paragraph __P ((WORD *finish));
  172. static void put_line __P ((WORD *w, int indent));
  173. static void put_word __P ((WORD *w));
  174. static void put_space __P ((int space));
  175.  
  176. /* The name this program was run with.  */
  177. const char *program_name;
  178.  
  179. /* If nonzero, display usage information and exit.  */
  180. static int show_help = 0;
  181.  
  182. /* If nonzero, print the version on standard output and exit.  */
  183. static int show_version = 0;
  184.  
  185. /* Option values.  */
  186.  
  187. /* If TRUE, first 2 lines may have different indent (default FALSE).  */
  188. static bool crown;
  189.  
  190. /* If TRUE, first 2 lines _must_ have different indent (default FALSE).  */
  191. static bool tagged;
  192.  
  193. /* If TRUE, each line is a paragraph on its own (default FALSE).  */
  194. static bool split;
  195.  
  196. /* If TRUE, don't preserve inter-word spacing (default FALSE).  */
  197. static bool uniform;
  198.  
  199. /* Prefix minus leading and trailing spaces (default "").  */
  200. static const char *prefix;
  201.  
  202. /* User-supplied maximum line width (default WIDTH).  The only output
  203.    lines
  204.    longer than this will each comprise a single word.  */
  205. static int max_width;
  206.  
  207. /* Values derived from the option values.  */
  208.  
  209. /* The length of prefix minus leading space.  */
  210. static int prefix_full_length;
  211.  
  212. /* The length of the leading space trimmed from the prefix.  */
  213. static int prefix_lead_space;
  214.  
  215. /* The length of prefix minus leading and trailing space.  */
  216. static int prefix_length;
  217.  
  218. /* The preferred width of text lines, set to LEEWAY % less than max_width.  */
  219. static int best_width;
  220.  
  221. /* Dynamic variables.  */
  222.  
  223. /* Start column of the character most recently read from the input file.  */
  224. static int in_column;
  225.  
  226. /* Start column of the next character to be written to stdout.  */
  227. static int out_column;
  228.  
  229. /* Space for the paragraph text -- longer paragraphs are handled neatly
  230.    (cf. flush_paragraph()).  */
  231. static char parabuf[MAXCHARS];
  232.  
  233. /* A pointer into parabuf, indicating the first unused character position.  */
  234. static char *wptr;
  235.  
  236. /* The words of a paragraph -- longer paragraphs are handled neatly
  237.    (cf. flush_paragraph()).  */
  238. static WORD word[MAXWORDS];
  239.  
  240. /* A pointer into the above word array, indicating the first position
  241.    after the last complete word.  Sometimes it will point at an incomplete
  242.    word.  */
  243. static WORD *word_limit;
  244.  
  245. /* If TRUE, current input file contains tab characters, and so tabs can be
  246.    used for white space on output.  */
  247. static bool tabs;
  248.  
  249. /* Space before trimmed prefix on each line of the current paragraph.  */
  250. static int prefix_indent;
  251.  
  252. /* Indentation of the first line of the current paragraph.  */
  253. static int first_indent;
  254.  
  255. /* Indentation of other lines of the current paragraph */
  256. static int other_indent;
  257.  
  258. /* To detect the end of a paragraph, we need to look ahead to the first
  259.    non-blank character after the prefix on the next line, or the first
  260.    character on the following line that failed to match the prefix.
  261.    We can reconstruct the lookahead from that character (next_char), its
  262.    position on the line (in_column) and the amount of space before the
  263.    prefix (next_prefix_indent).  See get_paragraph() and copy_rest().  */
  264.  
  265. /* The last character read from the input file.  */
  266. static int next_char;
  267.  
  268. /* The space before the trimmed prefix (or part of it) on the next line
  269.    after the current paragraph.  */
  270. static int next_prefix_indent;
  271.  
  272. /* If nonzero, the length of the last line output in the current
  273.    paragraph, used to charge for raggedness at the split point for long
  274.    paragraphs chosen by fmt_paragraph().  */
  275. static int last_line_length;
  276.  
  277. static void
  278. usage (int status)
  279. {
  280.   if (status != 0)
  281.     fprintf (stderr, _("Try `%s --help' for more information.\n"),
  282.          program_name);
  283.   else
  284.     {
  285.       printf (_("Usage: %s [-DIGITS] [OPTION]... [FILE]...\n"), program_name);
  286.       fputs (_("\
  287. Reformat each paragraph in the FILE(s), writing to standard output.\n\
  288. If no FILE or if FILE is `-', read standard input.\n\
  289. \n\
  290. Mandatory arguments to long options are mandatory for short options too.\n\
  291.   -c, --crown-margin        preserve indentation of first two lines\n\
  292.   -p, --prefix=STRING       combine only lines having STRING as prefix\n\
  293.   -s, --split-only          split long lines, but do not refill\n\
  294.   -t, --tagged-paragraph    indentation of first line different from second\n\
  295.   -u, --uniform-spacing     one space between words, two after sentences\n\
  296.   -w, --width=NUMBER        maximum line width (default of 75 columns)\n\
  297.       --help                display this help and exit\n\
  298.       --version             output version information and exit\n\
  299. \n\
  300. In -wNUMBER, the letter `w' may be omitted.\n"),
  301.          stdout);
  302.       puts (_("\nReport bugs to textutils-bugs@gnu.ai.mit.edu"));
  303.     }
  304.   exit (status == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
  305. }
  306.  
  307. /* Decode options and launch execution.  */
  308.  
  309. static const struct option long_options[] =
  310. {
  311.   {"crown-margin", no_argument, NULL, 'c'},
  312.   {"help", no_argument, &show_help, 1},
  313.   {"prefix", required_argument, NULL, 'p'},
  314.   {"split-only", no_argument, NULL, 's'},
  315.   {"tagged-paragraph", no_argument, NULL, 't'},
  316.   {"uniform-spacing", no_argument, NULL, 'u'},
  317.   {"version", no_argument, &show_version, 1},
  318.   {"width", required_argument, NULL, 'w'},
  319.   {0, 0, 0, 0},
  320. };
  321.  
  322. int
  323. main (register int argc, register char **argv)
  324. {
  325.   int optchar;
  326.   FILE *infile;
  327.  
  328. #ifdef __EMX__
  329. _wildcard(&argc, &argv);
  330. #endif
  331.  
  332.  
  333.   program_name = argv[0];
  334. #ifndef __EMX__
  335.   setlocale (LC_ALL, "");
  336.   bindtextdomain (PACKAGE, LOCALEDIR);
  337.   textdomain (PACKAGE);
  338. #endif
  339.   crown = tagged = split = uniform = FALSE;
  340.   max_width = WIDTH;
  341.   prefix = "";
  342.   prefix_length = prefix_lead_space = prefix_full_length = 0;
  343.  
  344.   if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
  345.     {
  346.       max_width = 0;
  347.       /* Old option syntax; a dash followed by one or more digits.
  348.          Move past the number. */
  349.       for (++argv[1]; ISDIGIT (*argv[1]); ++argv[1])
  350.     {
  351.       /* FIXME: use strtol to detect overflow.  */
  352.       max_width = max_width * 10 + *argv[1] - '0';
  353.     }
  354.       /* Make the options we just parsed invisible to getopt. */
  355.       argv[1] = argv[0];
  356.       argv++;
  357.       argc--;
  358.     }
  359.  
  360.   while ((optchar = getopt_long (argc, argv, "0123456789cstuw:p:",
  361.                  long_options, NULL))
  362.      != EOF)
  363.     switch (optchar)
  364.       {
  365.       default:
  366.     usage (1);
  367.  
  368.       case 0:
  369.     break;
  370.  
  371.       case 'c':
  372.     crown = TRUE;
  373.     break;
  374.  
  375.       case 's':
  376.     split = TRUE;
  377.     break;
  378.  
  379.       case 't':
  380.     tagged = TRUE;
  381.     break;
  382.  
  383.       case 'u':
  384.     uniform = TRUE;
  385.     break;
  386.  
  387.       case 'w':
  388.     {
  389.       long int tmp_long;
  390.       if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK
  391.           || tmp_long <= 0 || tmp_long > INT_MAX)
  392.         error (EXIT_FAILURE, 0, _("invalid line number increment: `%s'"),
  393.            optarg);
  394.       max_width = (int) tmp_long;
  395.     }
  396.     break;
  397.  
  398.       case 'p':
  399.     set_prefix (optarg);
  400.     break;
  401.  
  402.       }
  403.  
  404.   if (show_version)
  405.     {
  406.       printf ("fmt (%s) %s\n", GNU_PACKAGE, VERSION);
  407.       exit (EXIT_SUCCESS);
  408.     }
  409.  
  410.   if (show_help)
  411.     usage (0);
  412.  
  413.   best_width = max_width * (2 * (100 - LEEWAY) + 1) / 200;
  414.  
  415.   if (optind == argc)
  416.     fmt (stdin);
  417.   else
  418.     for (; optind < argc; optind++)
  419.       if (strcmp (argv[optind], "-") == 0)
  420.     fmt (stdin);
  421.       else
  422.     {
  423.       infile = fopen (argv[optind], "r");
  424.       if (infile != NULL)
  425.         {
  426.           fmt (infile);
  427.           fclose (infile);
  428.         }
  429.       else
  430.         error (0, errno, argv[optind]);
  431.     }
  432.  
  433.   exit (EXIT_SUCCESS);
  434. }
  435.  
  436. /* Trim space from the front and back of the string P, yielding the prefix,
  437.    and record the lengths of the prefix and the space trimmed.  */
  438.  
  439. static void
  440. set_prefix (register char *p)
  441. {
  442.   register char *s;
  443.  
  444.   prefix_lead_space = 0;
  445.   while (*p == ' ')
  446.     {
  447.       prefix_lead_space++;
  448.       p++;
  449.     }
  450.   prefix = p;
  451.   prefix_full_length = strlen (p);
  452.   s = p + prefix_full_length;
  453.   while (s > p && s[-1] == ' ')
  454.     s--;
  455.   *s = '\0';
  456.   prefix_length = s - p;
  457. }
  458.  
  459. /* read file F and send formatted output to stdout.  */
  460.  
  461. static void
  462. fmt (FILE *f)
  463. {
  464.   tabs = FALSE;
  465.   other_indent = 0;
  466.   next_char = get_prefix (f);
  467.   while (get_paragraph (f))
  468.     {
  469.       fmt_paragraph ();
  470.       put_paragraph (word_limit);
  471.     }
  472. }
  473.  
  474. /* Read a paragraph from input file F.  A paragraph consists of a
  475.    maximal number of non-blank (excluding any prefix) lines subject to:
  476.    * In split mode, a paragraph is a single non-blank line.
  477.    * In crown mode, the second and subsequent lines must have the
  478.    same indentation, but possibly different from the indent of the
  479.    first line.
  480.    * Tagged mode is similar, but the first and second lines must have
  481.    different indentations.
  482.    * Otherwise, all lines of a paragraph must have the same indent.
  483.    If a prefix is in effect, it must be present at the same indent for
  484.    each line in the paragraph.
  485.  
  486.    Return FALSE if end-of-file was encountered before the start of a
  487.    paragraph, else TRUE.  */
  488.  
  489. static bool
  490. get_paragraph (FILE *f)
  491. {
  492.   register int c;
  493.  
  494.   last_line_length = 0;
  495.   c = next_char;
  496.  
  497.   /* Scan (and copy) blank lines, and lines not introduced by the prefix.  */
  498.  
  499.   while (c == '\n' || c == EOF
  500.      || next_prefix_indent < prefix_lead_space
  501.      || in_column < next_prefix_indent + prefix_full_length)
  502.     {
  503.       c = copy_rest (f, c);
  504.       if (c == EOF)
  505.     {
  506.       next_char = EOF;
  507.       return FALSE;
  508.     }
  509.       putchar ('\n');
  510.       c = get_prefix (f);
  511.     }
  512.  
  513.   /* Got a suitable first line for a paragraph.  */
  514.  
  515.   prefix_indent = next_prefix_indent;
  516.   first_indent = in_column;
  517.   wptr = parabuf;
  518.   word_limit = word;
  519.   c = get_line (f, c);
  520.  
  521.   /* Read rest of paragraph (unless split is specified).  */
  522.  
  523.   if (split)
  524.     other_indent = first_indent;
  525.   else if (crown)
  526.     {
  527.       if (same_para (c))
  528.     {
  529.       other_indent = in_column;
  530.       do
  531.         {            /* for each line till the end of the para */
  532.           c = get_line (f, c);
  533.         }
  534.       while (same_para (c) && in_column == other_indent);
  535.     }
  536.       else
  537.     other_indent = first_indent;
  538.     }
  539.   else if (tagged)
  540.     {
  541.       if (same_para (c) && in_column != first_indent)
  542.     {
  543.       other_indent = in_column;
  544.       do
  545.         {            /* for each line till the end of the para */
  546.           c = get_line (f, c);
  547.         }
  548.       while (same_para (c) && in_column == other_indent);
  549.     }
  550.  
  551.       /* Only one line: use the secondary indent from last time if it
  552.          splits, or 0 if there have been no multi-line paragraphs in the
  553.          input so far.  But if these rules make the two indents the same,
  554.          pick a new secondary indent.  */
  555.  
  556.       else if (other_indent == first_indent)
  557.     other_indent = first_indent == 0 ? DEF_INDENT : 0;
  558.     }
  559.   else
  560.     {
  561.       other_indent = first_indent;
  562.       while (same_para (c) && in_column == other_indent)
  563.     c = get_line (f, c);
  564.     }
  565.   (word_limit - 1)->period = (word_limit - 1)->final = TRUE;
  566.   next_char = c;
  567.   return TRUE;
  568. }
  569.  
  570. /* Copy to the output a line that failed to match the prefix, or that
  571.    was blank after the prefix.  In the former case, C is the character
  572.    that failed to match the prefix.  In the latter, C is \n or EOF.
  573.    Return the character (\n or EOF) ending the line.  */
  574.  
  575. static int
  576. copy_rest (FILE *f, register int c)
  577. {
  578.   register const char *s;
  579.  
  580.   out_column = 0;
  581.   if (in_column > next_prefix_indent && c != '\n' && c != EOF)
  582.     {
  583.       put_space (next_prefix_indent);
  584.       for (s = prefix; out_column != in_column && *s; out_column++)
  585.     putchar (*s++);
  586.       put_space (in_column - out_column);
  587.     }
  588.   while (c != '\n' && c != EOF)
  589.     {
  590.       putchar (c);
  591.       c = getc (f);
  592.     }
  593.   return c;
  594. }
  595.  
  596. /* Return TRUE if a line whose first non-blank character after the
  597.    prefix (if any) is C could belong to the current paragraph,
  598.    otherwise FALSE.  */
  599.  
  600. static bool
  601. same_para (register int c)
  602. {
  603.   return (next_prefix_indent == prefix_indent
  604.       && in_column >= next_prefix_indent + prefix_full_length
  605.       && c != '\n' && c != EOF);
  606. }
  607.  
  608. /* Read a line from input file F, given first non-blank character C
  609.    after the prefix, and the following indent, and break it into words.
  610.    A word is a maximal non-empty string of non-white characters.  A word
  611.    ending in [.?!]["')\]]* and followed by end-of-line or at least two
  612.    spaces ends a sentence, as in emacs.
  613.  
  614.    Return the first non-blank character of the next line.  */
  615.  
  616. static int
  617. get_line (FILE *f, register int c)
  618. {
  619.   int start;
  620.   register char *end_of_parabuf;
  621.   register WORD *end_of_word;
  622.  
  623.   end_of_parabuf = ¶buf[MAXCHARS];
  624.   end_of_word = &word[MAXWORDS - 2];
  625.  
  626.   do
  627.     {                /* for each word in a line */
  628.  
  629.       /* Scan word.  */
  630.  
  631.       word_limit->text = wptr;
  632.       do
  633.     {
  634.       if (wptr == end_of_parabuf)
  635.         flush_paragraph ();
  636.       *wptr++ = c;
  637.       c = getc (f);
  638.     }
  639.       while (c != EOF && !ISSPACE (c));
  640.       in_column += word_limit->length = wptr - word_limit->text;
  641.       check_punctuation (word_limit);
  642.  
  643.       /* Scan inter-word space.  */
  644.  
  645.       start = in_column;
  646.       c = get_space (f, c);
  647.       word_limit->space = in_column - start;
  648.       word_limit->final = (c == EOF
  649.                || (word_limit->period
  650.                    && (c == '\n' || word_limit->space > 1)));
  651.       if (c == '\n' || c == EOF || uniform)
  652.     word_limit->space = word_limit->final ? 2 : 1;
  653.       if (word_limit == end_of_word)
  654.     flush_paragraph ();
  655.       word_limit++;
  656.       if (c == EOF)
  657.     return EOF;
  658.     }
  659.   while (c != '\n');
  660.   return get_prefix (f);
  661. }
  662.  
  663. /* Read a prefix from input file F.  Return either first non-matching
  664.    character, or first non-blank character after the prefix.  */
  665.  
  666. static int
  667. get_prefix (FILE *f)
  668. {
  669.   register int c;
  670.   register const char *p;
  671.  
  672.   in_column = 0;
  673.   c = get_space (f, getc (f));
  674.   if (prefix_length == 0)
  675.     next_prefix_indent = prefix_lead_space < in_column ?
  676.       prefix_lead_space : in_column;
  677.   else
  678.     {
  679.       next_prefix_indent = in_column;
  680.       for (p = prefix; *p != '\0'; p++)
  681.     {
  682.       if (c != *p)
  683.         return c;
  684.       in_column++;
  685.       c = getc (f);
  686.     }
  687.       c = get_space (f, c);
  688.     }
  689.   return c;
  690. }
  691.  
  692. /* Read blank characters from input file F, starting with C, and keeping
  693.    in_column up-to-date.  Return first non-blank character.  */
  694.  
  695. static int
  696. get_space (FILE *f, register int c)
  697. {
  698.   for (;;)
  699.     {
  700.       if (c == ' ')
  701.     in_column++;
  702.       else if (c == '\t')
  703.     {
  704.       tabs = TRUE;
  705.       in_column = (in_column / TABWIDTH + 1) * TABWIDTH;
  706.     }
  707.       else
  708.     return c;
  709.       c = getc (f);
  710.     }
  711. }
  712.  
  713. /* Set extra fields in word W describing any attached punctuation.  */
  714.  
  715. static void
  716. check_punctuation (register WORD *w)
  717. {
  718.   register const char *start, *finish;
  719.  
  720.   start = w->text;
  721.   finish = start + (w->length - 1);
  722.   w->paren = isopen (*start);
  723.   w->punct = ISPUNCT (*finish);
  724.   while (isclose (*finish) && finish > start)
  725.     finish--;
  726.   w->period = isperiod (*finish);
  727. }
  728.  
  729. /* Flush part of the paragraph to make room.  This function is called on
  730.    hitting the limit on the number of words or characters.  */
  731.  
  732. static void
  733. flush_paragraph (void)
  734. {
  735.   WORD *split_point;
  736.   register WORD *w;
  737.   int shift;
  738.   COST best_break;
  739.  
  740.   /* In the special case where it's all one word, just flush it.  */
  741.  
  742.   if (word_limit == word)
  743.     {
  744.       printf ("%*s", wptr - parabuf, parabuf);
  745.       wptr = parabuf;
  746.       return;
  747.     }
  748.  
  749.   /* Otherwise:
  750.      - format what you have so far as a paragraph,
  751.      - find a low-cost line break near the end,
  752.      - output to there,
  753.      - make that the start of the paragraph.  */
  754.  
  755.   fmt_paragraph ();
  756.  
  757.   /* Choose a good split point.  */
  758.  
  759.   split_point = word_limit;
  760.   best_break = MAXCOST;
  761.   for (w = word->next_break; w != word_limit; w = w->next_break)
  762.     {
  763.       if (w->best_cost - w->next_break->best_cost < best_break)
  764.     {
  765.       split_point = w;
  766.       best_break = w->best_cost - w->next_break->best_cost;
  767.     }
  768.       if (best_break <= MAXCOST - LINE_CREDIT)
  769.     best_break += LINE_CREDIT;
  770.     }
  771.   put_paragraph (split_point);
  772.  
  773.   /* Copy text of words down to start of parabuf -- we use memmove because
  774.      the source and target may overlap.  */
  775.  
  776.   memmove (parabuf, split_point->text, (size_t) (wptr - split_point->text));
  777.   shift = split_point->text - parabuf;
  778.   wptr -= shift;
  779.  
  780.   /* Adjust text pointers.  */
  781.  
  782.   for (w = split_point; w <= word_limit; w++)
  783.     w->text -= shift;
  784.  
  785.   /* Copy words from split_point down to word -- we use memmove because
  786.      the source and target may overlap.  */
  787.  
  788.   memmove ((char *) word, (char *) split_point,
  789.      (word_limit - split_point + 1) * sizeof (WORD));
  790.   word_limit -= split_point - word;
  791. }
  792.  
  793. /* Compute the optimal formatting for the whole paragraph by computing
  794.    and remembering the optimal formatting for each suffix from the empty
  795.    one to the whole paragraph.  */
  796.  
  797. static void
  798. fmt_paragraph (void)
  799. {
  800.   register WORD *start, *w;
  801.   register int len;
  802.   register COST wcost, best;
  803.   int saved_length;
  804.  
  805.   word_limit->best_cost = 0;
  806.   saved_length = word_limit->length;
  807.   word_limit->length = max_width;    /* sentinel */
  808.  
  809.   for (start = word_limit - 1; start >= word; start--)
  810.     {
  811.       best = MAXCOST;
  812.       len = start == word ? first_indent : other_indent;
  813.  
  814.       /* At least one word, however long, in the line.  */
  815.  
  816.       w = start;
  817.       len += w->length;
  818.       do
  819.     {
  820.       w++;
  821.  
  822.       /* Consider breaking before w.  */
  823.  
  824.       wcost = line_cost (w, len) + w->best_cost;
  825.       if (start == word && last_line_length > 0)
  826.         wcost += RAGGED_COST (len - last_line_length);
  827.       if (wcost < best)
  828.         {
  829.           best = wcost;
  830.           start->next_break = w;
  831.           start->line_length = len;
  832.         }
  833.       len += (w - 1)->space + w->length;    /* w > start >= word */
  834.     }
  835.       while (len < max_width);
  836.       start->best_cost = best + base_cost (start);
  837.     }
  838.  
  839.   word_limit->length = saved_length;
  840. }
  841.  
  842. /* Return the constant component of the cost of breaking before the
  843.    word THIS.  */
  844.  
  845. static COST
  846. base_cost (register WORD *this)
  847. {
  848.   register COST cost;
  849.  
  850.   cost = LINE_COST;
  851.  
  852.   if (this > word)
  853.     {
  854.       if ((this - 1)->period)
  855.     {
  856.       if ((this - 1)->final)
  857.         cost -= SENTENCE_BONUS;
  858.       else
  859.         cost += NOBREAK_COST;
  860.     }
  861.       else if ((this - 1)->punct)
  862.     cost -= PUNCT_BONUS;
  863.       else if (this > word + 1 && (this - 2)->final)
  864.     cost += WIDOW_COST ((this - 1)->length);
  865.     }
  866.  
  867.   if (this->paren)
  868.     cost -= PAREN_BONUS;
  869.   else if (this->final)
  870.     cost += ORPHAN_COST (this->length);
  871.  
  872.   return cost;
  873. }
  874.  
  875. /* Return the component of the cost of breaking before word NEXT that
  876.    depends on LEN, the length of the line beginning there.  */
  877.  
  878. static COST
  879. line_cost (register WORD *next, register int len)
  880. {
  881.   register int n;
  882.   register COST cost;
  883.  
  884.   if (next == word_limit)
  885.     return 0;
  886.   n = best_width - len;
  887.   cost = SHORT_COST (n);
  888.   if (next->next_break != word_limit)
  889.     {
  890.       n = len - next->line_length;
  891.       cost += RAGGED_COST (n);
  892.     }
  893.   return cost;
  894. }
  895.  
  896. /* Output to stdout a paragraph from word up to (but not including)
  897.    FINISH, which must be in the next_break chain from word.  */
  898.  
  899. static void
  900. put_paragraph (register WORD *finish)
  901. {
  902.   register WORD *w;
  903.  
  904.   put_line (word, first_indent);
  905.   for (w = word->next_break; w != finish; w = w->next_break)
  906.     put_line (w, other_indent);
  907. }
  908.  
  909. /* Output to stdout the line beginning with word W, beginning in column
  910.    INDENT, including the prefix (if any).  */
  911.  
  912. static void
  913. put_line (register WORD *w, int indent)
  914. {
  915.   register WORD *endline;
  916.  
  917.   out_column = 0;
  918.   put_space (prefix_indent);
  919.   fputs (prefix, stdout);
  920.   out_column += prefix_length;
  921.   put_space (indent - out_column);
  922.  
  923.   endline = w->next_break - 1;
  924.   for (; w != endline; w++)
  925.     {
  926.       put_word (w);
  927.       put_space (w->space);
  928.     }
  929.   put_word (w);
  930.   last_line_length = out_column;
  931.   putchar ('\n');
  932. }
  933.  
  934. /* Output to stdout the word W.  */
  935.  
  936. static void
  937. put_word (register WORD *w)
  938. {
  939.   register const char *s;
  940.   register int n;
  941.  
  942.   s = w->text;
  943.   for (n = w->length; n != 0; n--)
  944.     putchar (*s++);
  945.   out_column += w->length;
  946. }
  947.  
  948. /* Output to stdout SPACE spaces, or equivalent tabs.  */
  949.  
  950. static void
  951. put_space (int space)
  952. {
  953.   register int space_target, tab_target;
  954.  
  955.   space_target = out_column + space;
  956.   if (tabs)
  957.     {
  958.       tab_target = space_target / TABWIDTH * TABWIDTH;
  959.       if (out_column + 1 < tab_target)
  960.     while (out_column < tab_target)
  961.       {
  962.         putchar ('\t');
  963.         out_column = (out_column / TABWIDTH + 1) * TABWIDTH;
  964.       }
  965.     }
  966.   while (out_column < space_target)
  967.     {
  968.       putchar (' ');
  969.       out_column++;
  970.     }
  971. }
  972.