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