home *** CD-ROM | disk | FTP | other *** search
/ Fresh Fish 9 / FreshFishVol9-CD2.bin / bbs / gnu / textutils-1.11-src.lha / textutils-1.11 / src / fmt.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-11-02  |  24.4 KB  |  975 lines

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