dd: synchronize output after write errors
[coreutils.git] / src / fmt.c
blob1eb7019b047aaa31e4db6111b8efd680b036c8bf
1 /* GNU fmt -- simple text formatter.
2 Copyright (C) 1994-2022 Free Software Foundation, Inc.
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 3 of the License, or
7 (at your option) any later version.
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.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17 /* Written by Ross Paterson <rap@doc.ic.ac.uk>. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <sys/types.h>
22 #include <getopt.h>
23 #include <assert.h>
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
29 #include "system.h"
30 #include "error.h"
31 #include "die.h"
32 #include "fadvise.h"
33 #include "xdectoint.h"
35 /* The official name of this program (e.g., no 'g' prefix). */
36 #define PROGRAM_NAME "fmt"
38 #define AUTHORS proper_name ("Ross Paterson")
40 /* The following parameters represent the program's idea of what is
41 "best". Adjust to taste, subject to the caveats given. */
43 /* Default longest permitted line length (max_width). */
44 #define WIDTH 75
46 /* Prefer lines to be LEEWAY % shorter than the maximum width, giving
47 room for optimization. */
48 #define LEEWAY 7
50 /* The default secondary indent of tagged paragraph used for unindented
51 one-line paragraphs not preceded by any multi-line paragraphs. */
52 #define DEF_INDENT 3
54 /* Costs and bonuses are expressed as the equivalent departure from the
55 optimal line length, multiplied by 10. e.g. assigning something a
56 cost of 50 means that it is as bad as a line 5 characters too short
57 or too long. The definition of SHORT_COST(n) should not be changed.
58 However, EQUIV(n) may need tuning. */
60 /* FIXME: "fmt" misbehaves given large inputs or options. One
61 possible workaround for part of the problem is to change COST to be
62 a floating-point type. There are other problems besides COST,
63 though; see MAXWORDS below. */
65 typedef long int COST;
67 #define MAXCOST TYPE_MAXIMUM (COST)
69 #define SQR(n) ((n) * (n))
70 #define EQUIV(n) SQR ((COST) (n))
72 /* Cost of a filled line n chars longer or shorter than goal_width. */
73 #define SHORT_COST(n) EQUIV ((n) * 10)
75 /* Cost of the difference between adjacent filled lines. */
76 #define RAGGED_COST(n) (SHORT_COST (n) / 2)
78 /* Basic cost per line. */
79 #define LINE_COST EQUIV (70)
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))
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))
89 /* Bonus for breaking a line at the end of a sentence. */
90 #define SENTENCE_BONUS EQUIV (50)
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)
99 /* Bonus for breaking a line before open parenthesis. */
100 #define PAREN_BONUS EQUIV (40)
102 /* Bonus for breaking a line after other punctuation. */
103 #define PUNCT_BONUS EQUIV(40)
105 /* Credit for breaking a long paragraph one line later. */
106 #define LINE_CREDIT EQUIV(3)
108 /* Size of paragraph buffer, in words and characters. Longer paragraphs
109 are handled neatly (cf. flush_paragraph()), so long as these values
110 are considerably greater than required by the width. These values
111 cannot be extended indefinitely: doing so would run into size limits
112 and/or cause more overflows in cost calculations. FIXME: Remove these
113 arbitrary limits. */
115 #define MAXWORDS 1000
116 #define MAXCHARS 5000
118 /* Extra ctype(3)-style macros. */
120 #define isopen(c) (strchr ("(['`\"", c) != NULL)
121 #define isclose(c) (strchr (")]'\"", c) != NULL)
122 #define isperiod(c) (strchr (".?!", c) != NULL)
124 /* Size of a tab stop, for expansion on input and re-introduction on
125 output. */
126 #define TABWIDTH 8
128 /* Word descriptor structure. */
130 typedef struct Word WORD;
132 struct Word
135 /* Static attributes determined during input. */
137 char const *text; /* the text of the word */
138 int length; /* length of this word */
139 int space; /* the size of the following space */
140 unsigned int paren:1; /* starts with open paren */
141 unsigned int period:1; /* ends in [.?!])* */
142 unsigned int punct:1; /* ends in punctuation */
143 unsigned int final:1; /* end of sentence */
145 /* The remaining fields are computed during the optimization. */
147 int line_length; /* length of the best line starting here */
148 COST best_cost; /* cost of best paragraph starting here */
149 WORD *next_break; /* break which achieves best_cost */
152 /* Forward declarations. */
154 static void set_prefix (char *p);
155 static bool fmt (FILE *f, char const *);
156 static bool get_paragraph (FILE *f);
157 static int get_line (FILE *f, int c);
158 static int get_prefix (FILE *f);
159 static int get_space (FILE *f, int c);
160 static int copy_rest (FILE *f, int c);
161 static bool same_para (int c);
162 static void flush_paragraph (void);
163 static void fmt_paragraph (void);
164 static void check_punctuation (WORD *w);
165 static COST base_cost (WORD *this);
166 static COST line_cost (WORD *next, int len);
167 static void put_paragraph (WORD *finish);
168 static void put_line (WORD *w, int indent);
169 static void put_word (WORD *w);
170 static void put_space (int space);
172 /* Option values. */
174 /* If true, first 2 lines may have different indent (default false). */
175 static bool crown;
177 /* If true, first 2 lines _must_ have different indent (default false). */
178 static bool tagged;
180 /* If true, each line is a paragraph on its own (default false). */
181 static bool split;
183 /* If true, don't preserve inter-word spacing (default false). */
184 static bool uniform;
186 /* Prefix minus leading and trailing spaces (default ""). */
187 static char const *prefix;
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;
193 /* Values derived from the option values. */
195 /* The length of prefix minus leading space. */
196 static int prefix_full_length;
198 /* The length of the leading space trimmed from the prefix. */
199 static int prefix_lead_space;
201 /* The length of prefix minus leading and trailing space. */
202 static int prefix_length;
204 /* The preferred width of text lines, set to LEEWAY % less than max_width. */
205 static int goal_width;
207 /* Dynamic variables. */
209 /* Start column of the character most recently read from the input file. */
210 static int in_column;
212 /* Start column of the next character to be written to stdout. */
213 static int out_column;
215 /* Space for the paragraph text -- longer paragraphs are handled neatly
216 (cf. flush_paragraph()). */
217 static char parabuf[MAXCHARS];
219 /* A pointer into parabuf, indicating the first unused character position. */
220 static char *wptr;
222 /* The words of a paragraph -- longer paragraphs are handled neatly
223 (cf. flush_paragraph()). */
224 static WORD word[MAXWORDS];
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;
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;
235 /* Space before trimmed prefix on each line of the current paragraph. */
236 static int prefix_indent;
238 /* Indentation of the first line of the current paragraph. */
239 static int first_indent;
241 /* Indentation of other lines of the current paragraph */
242 static int other_indent;
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(). */
251 /* The last character read from the input file. */
252 static int next_char;
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;
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;
263 void
264 usage (int status)
266 if (status != EXIT_SUCCESS)
267 emit_try_help ();
268 else
270 printf (_("Usage: %s [-WIDTH] [OPTION]... [FILE]...\n"), program_name);
271 fputs (_("\
272 Reformat each paragraph in the FILE(s), writing to standard output.\n\
273 The option -WIDTH is an abbreviated form of --width=DIGITS.\n\
274 "), stdout);
276 emit_stdin_note ();
277 emit_mandatory_arg_note ();
279 fputs (_("\
280 -c, --crown-margin preserve indentation of first two lines\n\
281 -p, --prefix=STRING reformat only lines beginning with STRING,\n\
282 reattaching the prefix to reformatted lines\n\
283 -s, --split-only split long lines, but do not refill\n\
285 stdout);
286 /* Tell xgettext that the "% o" below is not a printf-style
287 format string: xgettext:no-c-format */
288 fputs (_("\
289 -t, --tagged-paragraph indentation of first line different from second\n\
290 -u, --uniform-spacing one space between words, two after sentences\n\
291 -w, --width=WIDTH maximum line width (default of 75 columns)\n\
292 -g, --goal=WIDTH goal width (default of 93% of width)\n\
293 "), stdout);
294 fputs (HELP_OPTION_DESCRIPTION, stdout);
295 fputs (VERSION_OPTION_DESCRIPTION, stdout);
296 emit_ancillary_info (PROGRAM_NAME);
298 exit (status);
301 /* Decode options and launch execution. */
303 static struct option const long_options[] =
305 {"crown-margin", no_argument, NULL, 'c'},
306 {"prefix", required_argument, NULL, 'p'},
307 {"split-only", no_argument, NULL, 's'},
308 {"tagged-paragraph", no_argument, NULL, 't'},
309 {"uniform-spacing", no_argument, NULL, 'u'},
310 {"width", required_argument, NULL, 'w'},
311 {"goal", required_argument, NULL, 'g'},
312 {GETOPT_HELP_OPTION_DECL},
313 {GETOPT_VERSION_OPTION_DECL},
314 {NULL, 0, NULL, 0},
318 main (int argc, char **argv)
320 int optchar;
321 bool ok = true;
322 char const *max_width_option = NULL;
323 char const *goal_width_option = NULL;
325 initialize_main (&argc, &argv);
326 set_program_name (argv[0]);
327 setlocale (LC_ALL, "");
328 bindtextdomain (PACKAGE, LOCALEDIR);
329 textdomain (PACKAGE);
331 atexit (close_stdout);
333 crown = tagged = split = uniform = false;
334 max_width = WIDTH;
335 prefix = "";
336 prefix_length = prefix_lead_space = prefix_full_length = 0;
338 if (argc > 1 && argv[1][0] == '-' && ISDIGIT (argv[1][1]))
340 /* Old option syntax; a dash followed by one or more digits. */
341 max_width_option = argv[1] + 1;
343 /* Make the option we just parsed invisible to getopt. */
344 argv[1] = argv[0];
345 argv++;
346 argc--;
349 while ((optchar = getopt_long (argc, argv, "0123456789cstuw:p:g:",
350 long_options, NULL))
351 != -1)
352 switch (optchar)
354 default:
355 if (ISDIGIT (optchar))
356 error (0, 0, _("invalid option -- %c; -WIDTH is recognized\
357 only when it is the first\noption; use -w N instead"),
358 optchar);
359 usage (EXIT_FAILURE);
361 case 'c':
362 crown = true;
363 break;
365 case 's':
366 split = true;
367 break;
369 case 't':
370 tagged = true;
371 break;
373 case 'u':
374 uniform = true;
375 break;
377 case 'w':
378 max_width_option = optarg;
379 break;
381 case 'g':
382 goal_width_option = optarg;
383 break;
385 case 'p':
386 set_prefix (optarg);
387 break;
389 case_GETOPT_HELP_CHAR;
391 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
395 if (max_width_option)
397 /* Limit max_width to MAXCHARS / 2; otherwise, the resulting
398 output can be quite ugly. */
399 max_width = xdectoumax (max_width_option, 0, MAXCHARS / 2, "",
400 _("invalid width"), 0);
403 if (goal_width_option)
405 /* Limit goal_width to max_width. */
406 goal_width = xdectoumax (goal_width_option, 0, max_width, "",
407 _("invalid width"), 0);
408 if (max_width_option == NULL)
409 max_width = goal_width + 10;
411 else
413 goal_width = max_width * (2 * (100 - LEEWAY) + 1) / 200;
416 bool have_read_stdin = false;
418 if (optind == argc)
420 have_read_stdin = true;
421 ok = fmt (stdin, "-");
423 else
425 for (; optind < argc; optind++)
427 char *file = argv[optind];
428 if (STREQ (file, "-"))
430 ok &= fmt (stdin, file);
431 have_read_stdin = true;
433 else
435 FILE *in_stream;
436 in_stream = fopen (file, "r");
437 if (in_stream != NULL)
438 ok &= fmt (in_stream, file);
439 else
441 error (0, errno, _("cannot open %s for reading"),
442 quoteaf (file));
443 ok = false;
449 if (have_read_stdin && fclose (stdin) != 0)
450 die (EXIT_FAILURE, errno, "%s", _("closing standard input"));
452 return ok ? EXIT_SUCCESS : EXIT_FAILURE;
455 /* Trim space from the front and back of the string P, yielding the prefix,
456 and record the lengths of the prefix and the space trimmed. */
458 static void
459 set_prefix (char *p)
461 char *s;
463 prefix_lead_space = 0;
464 while (*p == ' ')
466 prefix_lead_space++;
467 p++;
469 prefix = p;
470 prefix_full_length = strlen (p);
471 s = p + prefix_full_length;
472 while (s > p && s[-1] == ' ')
473 s--;
474 *s = '\0';
475 prefix_length = s - p;
478 /* Read F and send formatted output to stdout.
479 Close F when done, unless F is stdin. Diagnose input errors, using FILE.
480 If !F, assume F resulted from an fopen failure and diagnose that.
481 Return true if successful. */
483 static bool
484 fmt (FILE *f, char const *file)
486 fadvise (f, FADVISE_SEQUENTIAL);
487 tabs = false;
488 other_indent = 0;
489 next_char = get_prefix (f);
490 while (get_paragraph (f))
492 fmt_paragraph ();
493 put_paragraph (word_limit);
496 int err = ferror (f) ? 0 : -1;
497 if (f == stdin)
498 clearerr (f);
499 else if (fclose (f) != 0 && err < 0)
500 err = errno;
501 if (0 <= err)
502 error (0, err, err ? "%s" : _("read error"), quotef (file));
503 return err < 0;
506 /* Set the global variable 'other_indent' according to SAME_PARAGRAPH
507 and other global variables. */
509 static void
510 set_other_indent (bool same_paragraph)
512 if (split)
513 other_indent = first_indent;
514 else if (crown)
516 other_indent = (same_paragraph ? in_column : first_indent);
518 else if (tagged)
520 if (same_paragraph && in_column != first_indent)
522 other_indent = in_column;
525 /* Only one line: use the secondary indent from last time if it
526 splits, or 0 if there have been no multi-line paragraphs in the
527 input so far. But if these rules make the two indents the same,
528 pick a new secondary indent. */
530 else if (other_indent == first_indent)
531 other_indent = first_indent == 0 ? DEF_INDENT : 0;
533 else
535 other_indent = first_indent;
539 /* Read a paragraph from input file F. A paragraph consists of a
540 maximal number of non-blank (excluding any prefix) lines subject to:
541 * In split mode, a paragraph is a single non-blank line.
542 * In crown mode, the second and subsequent lines must have the
543 same indentation, but possibly different from the indent of the
544 first line.
545 * Tagged mode is similar, but the first and second lines must have
546 different indentations.
547 * Otherwise, all lines of a paragraph must have the same indent.
548 If a prefix is in effect, it must be present at the same indent for
549 each line in the paragraph.
551 Return false if end-of-file was encountered before the start of a
552 paragraph, else true. */
554 static bool
555 get_paragraph (FILE *f)
557 int c;
559 last_line_length = 0;
560 c = next_char;
562 /* Scan (and copy) blank lines, and lines not introduced by the prefix. */
564 while (c == '\n' || c == EOF
565 || next_prefix_indent < prefix_lead_space
566 || in_column < next_prefix_indent + prefix_full_length)
568 c = copy_rest (f, c);
569 if (c == EOF)
571 next_char = EOF;
572 return false;
574 putchar ('\n');
575 c = get_prefix (f);
578 /* Got a suitable first line for a paragraph. */
580 prefix_indent = next_prefix_indent;
581 first_indent = in_column;
582 wptr = parabuf;
583 word_limit = word;
584 c = get_line (f, c);
585 set_other_indent (same_para (c));
587 /* Read rest of paragraph (unless split is specified). */
589 if (split)
591 /* empty */
593 else if (crown)
595 if (same_para (c))
598 { /* for each line till the end of the para */
599 c = get_line (f, c);
601 while (same_para (c) && in_column == other_indent);
604 else if (tagged)
606 if (same_para (c) && in_column != first_indent)
609 { /* for each line till the end of the para */
610 c = get_line (f, c);
612 while (same_para (c) && in_column == other_indent);
615 else
617 while (same_para (c) && in_column == other_indent)
618 c = get_line (f, c);
621 /* Tell static analysis tools that using word_limit[-1] is ok.
622 word_limit is guaranteed to have been incremented by get_line. */
623 assert (word < word_limit);
625 (word_limit - 1)->period = (word_limit - 1)->final = true;
626 next_char = c;
627 return true;
630 /* Copy to the output a line that failed to match the prefix, or that
631 was blank after the prefix. In the former case, C is the character
632 that failed to match the prefix. In the latter, C is \n or EOF.
633 Return the character (\n or EOF) ending the line. */
635 static int
636 copy_rest (FILE *f, int c)
638 char const *s;
640 out_column = 0;
641 if (in_column > next_prefix_indent || (c != '\n' && c != EOF))
643 put_space (next_prefix_indent);
644 for (s = prefix; out_column != in_column && *s; out_column++)
645 putchar (*s++);
646 if (c != EOF && c != '\n')
647 put_space (in_column - out_column);
648 if (c == EOF && in_column >= next_prefix_indent + prefix_length)
649 putchar ('\n');
651 while (c != '\n' && c != EOF)
653 putchar (c);
654 c = getc (f);
656 return c;
659 /* Return true if a line whose first non-blank character after the
660 prefix (if any) is C could belong to the current paragraph,
661 otherwise false. */
663 static bool
664 same_para (int c)
666 return (next_prefix_indent == prefix_indent
667 && in_column >= next_prefix_indent + prefix_full_length
668 && c != '\n' && c != EOF);
671 /* Read a line from input file F, given first non-blank character C
672 after the prefix, and the following indent, and break it into words.
673 A word is a maximal non-empty string of non-white characters. A word
674 ending in [.?!]["')\]]* and followed by end-of-line or at least two
675 spaces ends a sentence, as in emacs.
677 Return the first non-blank character of the next line. */
679 static int
680 get_line (FILE *f, int c)
682 int start;
683 char *end_of_parabuf;
684 WORD *end_of_word;
686 end_of_parabuf = &parabuf[MAXCHARS];
687 end_of_word = &word[MAXWORDS - 2];
690 { /* for each word in a line */
692 /* Scan word. */
694 word_limit->text = wptr;
697 if (wptr == end_of_parabuf)
699 set_other_indent (true);
700 flush_paragraph ();
702 *wptr++ = c;
703 c = getc (f);
705 while (c != EOF && !isspace (c));
706 in_column += word_limit->length = wptr - word_limit->text;
707 check_punctuation (word_limit);
709 /* Scan inter-word space. */
711 start = in_column;
712 c = get_space (f, c);
713 word_limit->space = in_column - start;
714 word_limit->final = (c == EOF
715 || (word_limit->period
716 && (c == '\n' || word_limit->space > 1)));
717 if (c == '\n' || c == EOF || uniform)
718 word_limit->space = word_limit->final ? 2 : 1;
719 if (word_limit == end_of_word)
721 set_other_indent (true);
722 flush_paragraph ();
724 word_limit++;
726 while (c != '\n' && c != EOF);
727 return get_prefix (f);
730 /* Read a prefix from input file F. Return either first non-matching
731 character, or first non-blank character after the prefix. */
733 static int
734 get_prefix (FILE *f)
736 int c;
738 in_column = 0;
739 c = get_space (f, getc (f));
740 if (prefix_length == 0)
741 next_prefix_indent = prefix_lead_space < in_column ?
742 prefix_lead_space : in_column;
743 else
745 char const *p;
746 next_prefix_indent = in_column;
747 for (p = prefix; *p != '\0'; p++)
749 unsigned char pc = *p;
750 if (c != pc)
751 return c;
752 in_column++;
753 c = getc (f);
755 c = get_space (f, c);
757 return c;
760 /* Read blank characters from input file F, starting with C, and keeping
761 in_column up-to-date. Return first non-blank character. */
763 static int
764 get_space (FILE *f, int c)
766 while (true)
768 if (c == ' ')
769 in_column++;
770 else if (c == '\t')
772 tabs = true;
773 in_column = (in_column / TABWIDTH + 1) * TABWIDTH;
775 else
776 return c;
777 c = getc (f);
781 /* Set extra fields in word W describing any attached punctuation. */
783 static void
784 check_punctuation (WORD *w)
786 char const *start = w->text;
787 char const *finish = start + (w->length - 1);
788 unsigned char fin = *finish;
790 w->paren = isopen (*start);
791 w->punct = !! ispunct (fin);
792 while (start < finish && isclose (*finish))
793 finish--;
794 w->period = isperiod (*finish);
797 /* Flush part of the paragraph to make room. This function is called on
798 hitting the limit on the number of words or characters. */
800 static void
801 flush_paragraph (void)
803 WORD *split_point;
804 WORD *w;
805 int shift;
806 COST best_break;
808 /* In the special case where it's all one word, just flush it. */
810 if (word_limit == word)
812 fwrite (parabuf, sizeof *parabuf, wptr - parabuf, stdout);
813 wptr = parabuf;
814 return;
817 /* Otherwise:
818 - format what you have so far as a paragraph,
819 - find a low-cost line break near the end,
820 - output to there,
821 - make that the start of the paragraph. */
823 fmt_paragraph ();
825 /* Choose a good split point. */
827 split_point = word_limit;
828 best_break = MAXCOST;
829 for (w = word->next_break; w != word_limit; w = w->next_break)
831 if (w->best_cost - w->next_break->best_cost < best_break)
833 split_point = w;
834 best_break = w->best_cost - w->next_break->best_cost;
836 if (best_break <= MAXCOST - LINE_CREDIT)
837 best_break += LINE_CREDIT;
839 put_paragraph (split_point);
841 /* Copy text of words down to start of parabuf -- we use memmove because
842 the source and target may overlap. */
844 memmove (parabuf, split_point->text, wptr - split_point->text);
845 shift = split_point->text - parabuf;
846 wptr -= shift;
848 /* Adjust text pointers. */
850 for (w = split_point; w <= word_limit; w++)
851 w->text -= shift;
853 /* Copy words from split_point down to word -- we use memmove because
854 the source and target may overlap. */
856 memmove (word, split_point, (word_limit - split_point + 1) * sizeof *word);
857 word_limit -= split_point - word;
860 /* Compute the optimal formatting for the whole paragraph by computing
861 and remembering the optimal formatting for each suffix from the empty
862 one to the whole paragraph. */
864 static void
865 fmt_paragraph (void)
867 WORD *start, *w;
868 int len;
869 COST wcost, best;
870 int saved_length;
872 word_limit->best_cost = 0;
873 saved_length = word_limit->length;
874 word_limit->length = max_width; /* sentinel */
876 for (start = word_limit - 1; start >= word; start--)
878 best = MAXCOST;
879 len = start == word ? first_indent : other_indent;
881 /* At least one word, however long, in the line. */
883 w = start;
884 len += w->length;
887 w++;
889 /* Consider breaking before w. */
891 wcost = line_cost (w, len) + w->best_cost;
892 if (start == word && last_line_length > 0)
893 wcost += RAGGED_COST (len - last_line_length);
894 if (wcost < best)
896 best = wcost;
897 start->next_break = w;
898 start->line_length = len;
901 /* This is a kludge to keep us from computing 'len' as the
902 sum of the sentinel length and some non-zero number.
903 Since the sentinel w->length may be INT_MAX, adding
904 to that would give a negative result. */
905 if (w == word_limit)
906 break;
908 len += (w - 1)->space + w->length; /* w > start >= word */
910 while (len < max_width);
911 start->best_cost = best + base_cost (start);
914 word_limit->length = saved_length;
917 /* Return the constant component of the cost of breaking before the
918 word THIS. */
920 static COST
921 base_cost (WORD *this)
923 COST cost;
925 cost = LINE_COST;
927 if (this > word)
929 if ((this - 1)->period)
931 if ((this - 1)->final)
932 cost -= SENTENCE_BONUS;
933 else
934 cost += NOBREAK_COST;
936 else if ((this - 1)->punct)
937 cost -= PUNCT_BONUS;
938 else if (this > word + 1 && (this - 2)->final)
939 cost += WIDOW_COST ((this - 1)->length);
942 if (this->paren)
943 cost -= PAREN_BONUS;
944 else if (this->final)
945 cost += ORPHAN_COST (this->length);
947 return cost;
950 /* Return the component of the cost of breaking before word NEXT that
951 depends on LEN, the length of the line beginning there. */
953 static COST
954 line_cost (WORD *next, int len)
956 int n;
957 COST cost;
959 if (next == word_limit)
960 return 0;
961 n = goal_width - len;
962 cost = SHORT_COST (n);
963 if (next->next_break != word_limit)
965 n = len - next->line_length;
966 cost += RAGGED_COST (n);
968 return cost;
971 /* Output to stdout a paragraph from word up to (but not including)
972 FINISH, which must be in the next_break chain from word. */
974 static void
975 put_paragraph (WORD *finish)
977 WORD *w;
979 put_line (word, first_indent);
980 for (w = word->next_break; w != finish; w = w->next_break)
981 put_line (w, other_indent);
984 /* Output to stdout the line beginning with word W, beginning in column
985 INDENT, including the prefix (if any). */
987 static void
988 put_line (WORD *w, int indent)
990 WORD *endline;
992 out_column = 0;
993 put_space (prefix_indent);
994 fputs (prefix, stdout);
995 out_column += prefix_length;
996 put_space (indent - out_column);
998 endline = w->next_break - 1;
999 for (; w != endline; w++)
1001 put_word (w);
1002 put_space (w->space);
1004 put_word (w);
1005 last_line_length = out_column;
1006 putchar ('\n');
1009 /* Output to stdout the word W. */
1011 static void
1012 put_word (WORD *w)
1014 char const *s;
1015 int n;
1017 s = w->text;
1018 for (n = w->length; n != 0; n--)
1019 putchar (*s++);
1020 out_column += w->length;
1023 /* Output to stdout SPACE spaces, or equivalent tabs. */
1025 static void
1026 put_space (int space)
1028 int space_target, tab_target;
1030 space_target = out_column + space;
1031 if (tabs)
1033 tab_target = space_target / TABWIDTH * TABWIDTH;
1034 if (out_column + 1 < tab_target)
1035 while (out_column < tab_target)
1037 putchar ('\t');
1038 out_column = (out_column / TABWIDTH + 1) * TABWIDTH;
1041 while (out_column < space_target)
1043 putchar (' ');
1044 out_column++;