1 /* $OpenBSD: fmt.c,v 1.27 2009/10/27 23:59:38 deraadt Exp $ */ 2 3 /* Sensible version of fmt 4 * 5 * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ] 6 * 7 * Since the documentation for the original fmt is so poor, here 8 * is an accurate description of what this one does. It's usually 9 * the same. The *mechanism* used may differ from that suggested 10 * here. Note that we are *not* entirely compatible with fmt, 11 * because fmt gets so many things wrong. 12 * 13 * 1. Tabs are expanded, assuming 8-space tab stops. 14 * If the `-t <n>' option is given, we assume <n>-space 15 * tab stops instead. 16 * Trailing blanks are removed from all lines. 17 * x\b == nothing, for any x other than \b. 18 * Other control characters are simply stripped. This 19 * includes \r. 20 * 2. Each line is split into leading whitespace and 21 * everything else. Maximal consecutive sequences of 22 * lines with the same leading whitespace are considered 23 * to form paragraphs, except that a blank line is always 24 * a paragraph to itself. 25 * If the `-p' option is given then the first line of a 26 * paragraph is permitted to have indentation different 27 * from that of the other lines. 28 * If the `-m' option is given then a line that looks 29 * like a mail message header, if it is not immediately 30 * preceded by a non-blank non-message-header line, is 31 * taken to start a new paragraph, which also contains 32 * any subsequent lines with non-empty leading whitespace. 33 * Unless the `-n' option is given, lines beginning with 34 * a . (dot) are not formatted. 35 * 3. The "everything else" is split into words; a word 36 * includes its trailing whitespace, and a word at the 37 * end of a line is deemed to be followed by a single 38 * space, or two spaces if it ends with a sentence-end 39 * character. (See the `-d' option for how to change that.) 40 * If the `-s' option has been given, then a word's trailing 41 * whitespace is replaced by what it would have had if it 42 * had occurred at end of line. 43 * 4. Each paragraph is sent to standard output as follows. 44 * We output the leading whitespace, and then enough words 45 * to make the line length as near as possible to the goal 46 * without exceeding the maximum. (If a single word would 47 * exceed the maximum, we output that anyway.) Of course 48 * the trailing whitespace of the last word is ignored. 49 * We then emit a newline and start again if there are any 50 * words left. 51 * Note that for a blank line this translates as "We emit 52 * a newline". 53 * If the `-l <n>' option is given, then leading whitespace 54 * is modified slightly: <n> spaces are replaced by a tab. 55 * Indented paragraphs (see above under `-p') make matters 56 * more complicated than this suggests. Actually every paragraph 57 * has two `leading whitespace' values; the value for the first 58 * line, and the value for the most recent line. (While processing 59 * the first line, the two are equal. When `-p' has not been 60 * given, they are always equal.) The leading whitespace 61 * actually output is that of the first line (for the first 62 * line of *output*) or that of the most recent line (for 63 * all other lines of output). 64 * When `-m' has been given, message header paragraphs are 65 * taken as having first-leading-whitespace empty and 66 * subsequent-leading-whitespace two spaces. 67 * 68 * Multiple input files are formatted one at a time, so that a file 69 * never ends in the middle of a line. 70 * 71 * There's an alternative mode of operation, invoked by giving 72 * the `-c' option. In that case we just center every line, 73 * and most of the other options are ignored. This should 74 * really be in a separate program, but we must stay compatible 75 * with old `fmt'. 76 * 77 * QUERY: Should `-m' also try to do the right thing with quoted text? 78 * QUERY: `-b' to treat backslashed whitespace as old `fmt' does? 79 * QUERY: Option meaning `never join lines'? 80 * QUERY: Option meaning `split in mid-word to avoid overlong lines'? 81 * (Those last two might not be useful, since we have `fold'.) 82 * 83 * Differences from old `fmt': 84 * 85 * - We have many more options. Options that aren't understood 86 * generate a lengthy usage message, rather than being 87 * treated as filenames. 88 * - Even with `-m', our handling of message headers is 89 * significantly different. (And much better.) 90 * - We don't treat `\ ' as non-word-breaking. 91 * - Downward changes of indentation start new paragraphs 92 * for us, as well as upward. (I think old `fmt' behaves 93 * in the way it does in order to allow indented paragraphs, 94 * but this is a broken way of making indented paragraphs 95 * behave right.) 96 * - Given the choice of going over or under |goal_length| 97 * by the same amount, we go over; old `fmt' goes under. 98 * - We treat `?' as ending a sentence, and not `:'. Old `fmt' 99 * does the reverse. 100 * - We return approved return codes. Old `fmt' returns 101 * 1 for some errors, and *the number of unopenable files* 102 * when that was all that went wrong. 103 * - We have fewer crashes and more helpful error messages. 104 * - We don't turn spaces into tabs at starts of lines unless 105 * specifically requested. 106 * - New `fmt' is somewhat smaller and slightly faster than 107 * old `fmt'. 108 * 109 * Bugs: 110 * 111 * None known. There probably are some, though. 112 * 113 * Portability: 114 * 115 * I believe this code to be pretty portable. It does require 116 * that you have `getopt'. If you need to include "getopt.h" 117 * for this (e.g., if your system didn't come with `getopt' 118 * and you installed it yourself) then you should arrange for 119 * NEED_getopt_h to be #defined. 120 * 121 * Everything here should work OK even on nasty 16-bit 122 * machines and nice 64-bit ones. However, it's only really 123 * been tested on my FreeBSD machine. Your mileage may vary. 124 */ 125 126 /* Copyright (c) 1997 Gareth McCaughan. All rights reserved. 127 * 128 * Redistribution and use of this code, in source or binary forms, 129 * with or without modification, are permitted subject to the following 130 * conditions: 131 * 132 * - Redistribution of source code must retain the above copyright 133 * notice, this list of conditions and the following disclaimer. 134 * 135 * - If you distribute modified source code it must also include 136 * a notice saying that it has been modified, and giving a brief 137 * description of what changes have been made. 138 * 139 * Disclaimer: I am not responsible for the results of using this code. 140 * If it formats your hard disc, sends obscene messages to 141 * your boss and kills your children then that's your problem 142 * not mine. I give absolutely no warranty of any sort as to 143 * what the program will do, and absolutely refuse to be held 144 * liable for any consequences of your using it. 145 * Thank you. Have a nice day. 146 */ 147 148 /* RCS change log: 149 * Revision 1.5 1998/03/02 18:02:21 gjm11 150 * Minor changes for portability. 151 * 152 * Revision 1.4 1997/10/01 11:51:28 gjm11 153 * Repair broken indented-paragraph handling. 154 * Add mail message header stuff. 155 * Improve comments and layout. 156 * Make usable with non-BSD systems. 157 * Add revision display to usage message. 158 * 159 * Revision 1.3 1997/09/30 16:24:47 gjm11 160 * Add copyright notice, rcsid string and log message. 161 * 162 * Revision 1.2 1997/09/30 16:13:39 gjm11 163 * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h . 164 * Parse options with `getopt'. Clean up code generally. 165 * Make comments more accurate. 166 * 167 * Revision 1.1 1997/09/30 11:29:57 gjm11 168 * Initial revision 169 */ 170 171 #include <ctype.h> 172 #include <err.h> 173 #include <locale.h> 174 #include <stdio.h> 175 #include <stdlib.h> 176 #include <string.h> 177 #include <sysexits.h> 178 #include <unistd.h> 179 180 /* Something that, we hope, will never be a genuine line length, 181 * indentation etc. 182 */ 183 #define SILLY ((size_t)-1) 184 185 /* I used to use |strtoul| for this, but (1) not all systems have it 186 * and (2) it's probably better to use |strtol| to detect negative 187 * numbers better. 188 * If |fussyp==0| then we don't complain about non-numbers 189 * (returning 0 instead), but we do complain about bad numbers. 190 */ 191 static size_t 192 get_positive(const char *s, const char *err_mess, int fussyP) 193 { 194 char *t; 195 long result = strtol(s, &t, 0); 196 197 if (*t) { 198 if (fussyP) 199 goto Lose; 200 else 201 return 0; 202 } 203 if (result <= 0) { 204 Lose: 205 errx(EX_USAGE, "%s", err_mess); 206 } 207 208 return (size_t) result; 209 } 210 211 /* Global variables */ 212 213 static int centerP = 0; /* Try to center lines? */ 214 static size_t goal_length = 0; /* Target length for output lines */ 215 static size_t max_length = 0; /* Maximum length for output lines */ 216 static int coalesce_spaces_P = 0; /* Coalesce multiple whitespace -> ' ' ? */ 217 static int allow_indented_paragraphs = 0; /* Can first line have diff. ind.? */ 218 static int tab_width = 8; /* Number of spaces per tab stop */ 219 static size_t output_tab_width = 0; /* Ditto, when squashing leading spaces */ 220 static const char *sentence_enders = ".?!"; /* Double-space after these */ 221 static int grok_mail_headers = 0; /* treat embedded mail headers magically? */ 222 static int format_troff = 0; /* Format troff? */ 223 224 static int n_errors = 0; /* Number of failed files. Return on exit. */ 225 static char *output_buffer = NULL; /* Output line will be built here */ 226 static size_t x; /* Horizontal position in output line */ 227 static size_t x0; /* Ditto, ignoring leading whitespace */ 228 static size_t pending_spaces; /* Spaces to add before next word */ 229 static int output_in_paragraph = 0; /* Any of current para written out yet? */ 230 231 /* Prototypes */ 232 233 static void process_named_file(const char *); 234 static void process_stream(FILE *, const char *); 235 static size_t indent_length(const char *, size_t); 236 static int might_be_header(const unsigned char *); 237 static void new_paragraph(size_t, size_t); 238 static void output_word(size_t, size_t, const char *, size_t, size_t); 239 static void output_indent(size_t); 240 static void center_stream(FILE *, const char *); 241 static char *get_line(FILE *, size_t *); 242 static void *xrealloc(void *, size_t); 243 void usage(void); 244 245 #define XMALLOC(x) xrealloc(0, x) 246 247 /* Here is perhaps the right place to mention that this code is 248 * all in top-down order. Hence, |main| comes first. 249 */ 250 int 251 main(int argc, char *argv[]) 252 { 253 int ch; /* used for |getopt| processing */ 254 255 (void)setlocale(LC_CTYPE, ""); 256 257 /* 1. Grok parameters. */ 258 while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) { 259 switch (ch) { 260 case 'c': 261 centerP = 1; 262 break; 263 case 'd': 264 sentence_enders = optarg; 265 break; 266 case 'l': 267 output_tab_width 268 = get_positive(optarg, "output tab width must be positive", 1); 269 break; 270 case 'm': 271 grok_mail_headers = 1; 272 break; 273 case 'n': 274 format_troff = 1; 275 break; 276 case 'p': 277 allow_indented_paragraphs = 1; 278 break; 279 case 's': 280 coalesce_spaces_P = 1; 281 break; 282 case 't': 283 tab_width = get_positive(optarg, "tab width must be positive", 1); 284 break; 285 case 'w': 286 goal_length = get_positive(optarg, "width must be positive", 1); 287 max_length = goal_length; 288 break; 289 case '0': case '1': case '2': case '3': case '4': case '5': 290 case '6': case '7': case '8': case '9': 291 /* XXX this is not a stylistically approved use of getopt() */ 292 if (goal_length == 0) { 293 char *p; 294 295 p = argv[optind - 1]; 296 if (p[0] == '-' && p[1] == ch && !p[2]) 297 goal_length = get_positive(++p, "width must be nonzero", 1); 298 else 299 goal_length = get_positive(argv[optind]+1, 300 "width must be nonzero", 1); 301 max_length = goal_length; 302 } 303 break; 304 case 'h': 305 default: 306 usage(); 307 /* NOT REACHED */ 308 } 309 } 310 311 argc -= optind; 312 argv += optind; 313 314 /* [ goal [ maximum ] ] */ 315 if (argc > 0 && goal_length == 0 && 316 (goal_length = get_positive(*argv,"goal length must be positive", 0)) != 0) { 317 --argc; 318 ++argv; 319 if (argc > 0 && (max_length = get_positive(*argv,"max length must be positive", 0)) != 0) { 320 --argc; 321 ++argv; 322 if (max_length < goal_length) 323 errx(EX_USAGE, "max length must be >= goal length"); 324 } 325 } 326 327 if (goal_length == 0) 328 goal_length = 65; 329 if (max_length == 0) 330 max_length = goal_length+10; 331 output_buffer = XMALLOC(max_length+1); /* really needn't be longer */ 332 333 /* 2. Process files. */ 334 335 if (argc > 0) { 336 while (argc-- > 0) 337 process_named_file(*argv++); 338 } else { 339 process_stream(stdin, "standard input"); 340 } 341 342 /* We're done. */ 343 return n_errors ? EX_NOINPUT : 0; 344 345 } 346 347 /* Process a single file, given its name. 348 */ 349 static void 350 process_named_file(const char *name) 351 { 352 FILE *f; 353 354 if ((f = fopen(name, "r")) == NULL) { 355 warn("%s", name); 356 ++n_errors; 357 } else { 358 process_stream(f, name); 359 fclose(f); 360 } 361 } 362 363 /* Types of mail header continuation lines: 364 */ 365 typedef enum { 366 hdr_ParagraphStart = -1, 367 hdr_NonHeader = 0, 368 hdr_Header = 1, 369 hdr_Continuation = 2 370 } HdrType; 371 372 /* Process a stream. This is where the real work happens, 373 * except that centering is handled separately. 374 */ 375 static void 376 process_stream(FILE *stream, const char *name) 377 { 378 size_t n; 379 size_t np; 380 size_t last_indent = SILLY; /* how many spaces in last indent? */ 381 size_t para_line_number = 0; /* how many lines already read in this para? */ 382 size_t first_indent = SILLY; /* indentation of line 0 of paragraph */ 383 HdrType prev_header_type = hdr_ParagraphStart; 384 HdrType header_type; 385 386 /* ^-- header_type of previous line; -1 at para start */ 387 char *line; 388 size_t length; 389 390 if (centerP) { 391 center_stream(stream, name); 392 return; 393 } 394 395 while ((line = get_line(stream, &length)) != NULL) { 396 np = indent_length(line, length); 397 header_type = hdr_NonHeader; 398 if (grok_mail_headers && prev_header_type != hdr_NonHeader) { 399 if (np == 0 && might_be_header(line)) 400 header_type = hdr_Header; 401 else if (np > 0 && prev_header_type>hdr_NonHeader) 402 header_type = hdr_Continuation; 403 } 404 405 /* We need a new paragraph if and only if: 406 * this line is blank, 407 * OR it's a troff request, 408 * OR it's a mail header, 409 * OR it's not a mail header AND the last line was one, 410 * OR the indentation has changed 411 * AND the line isn't a mail header continuation line 412 * AND this isn't the second line of an indented paragraph. 413 */ 414 if (length == 0 || (line[0] == '.' && !format_troff) || 415 header_type == hdr_Header || 416 (header_type == hdr_NonHeader && prev_header_type > hdr_NonHeader) || 417 (np != last_indent && header_type != hdr_Continuation && 418 (!allow_indented_paragraphs || para_line_number != 1)) ) { 419 new_paragraph(output_in_paragraph ? last_indent : first_indent, np); 420 para_line_number = 0; 421 first_indent = np; 422 last_indent = np; 423 424 /* nroff compatibility */ 425 if (length > 0 && line[0] == '.' && !format_troff) { 426 printf("%.*s\n", (int)length, line); 427 continue; 428 } 429 if (header_type == hdr_Header) 430 last_indent = 2; /* for cont. lines */ 431 if (length == 0) { 432 putchar('\n'); 433 prev_header_type = hdr_ParagraphStart; 434 continue; 435 } else { 436 /* If this is an indented paragraph other than a mail header 437 * continuation, set |last_indent|. 438 */ 439 if (np != last_indent && header_type != hdr_Continuation) 440 last_indent = np; 441 } 442 prev_header_type = header_type; 443 } 444 445 n = np; 446 while (n < length) { 447 /* Find word end and count spaces after it */ 448 size_t word_length = 0, space_length = 0; 449 while (n+word_length < length && line[n+word_length] != ' ') 450 ++word_length; 451 space_length = word_length; 452 while (n+space_length < length && line[n+space_length] == ' ') 453 ++space_length; 454 /* Send the word to the output machinery. */ 455 output_word(first_indent, last_indent, 456 line+n, word_length, space_length-word_length); 457 n += space_length; 458 } 459 ++para_line_number; 460 } 461 462 new_paragraph(output_in_paragraph ? last_indent : first_indent, 0); 463 if (ferror(stream)) { 464 warn("%s", name); 465 ++n_errors; 466 } 467 } 468 469 /* How long is the indent on this line? 470 */ 471 static size_t 472 indent_length(const char *line, size_t length) 473 { 474 size_t n = 0; 475 476 while (n < length && *line++ == ' ') 477 ++n; 478 return n; 479 } 480 481 /* Might this line be a mail header? 482 * We deem a line to be a possible header if it matches the 483 * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same 484 * as in RFC whatever-number-it-is; we want to be gratuitously 485 * conservative to avoid mangling ordinary civilised text. 486 */ 487 static int 488 might_be_header(const unsigned char *line) 489 { 490 491 if (!isupper(*line++)) 492 return 0; 493 while (isalnum(*line) || *line == '-') 494 ++line; 495 return (*line == ':' && isspace(line[1])); 496 } 497 498 /* Begin a new paragraph with an indent of |indent| spaces. 499 */ 500 static void 501 new_paragraph(size_t old_indent, size_t indent) 502 { 503 504 if (x0) { 505 if (old_indent > 0) 506 output_indent(old_indent); 507 fwrite(output_buffer, 1, x0, stdout); 508 putchar('\n'); 509 } 510 x = indent; 511 x0 = 0; 512 pending_spaces = 0; 513 output_in_paragraph = 0; 514 } 515 516 /* Output spaces or tabs for leading indentation. 517 */ 518 static void 519 output_indent(size_t n_spaces) 520 { 521 522 if (output_tab_width) { 523 while (n_spaces >= output_tab_width) { 524 putchar('\t'); 525 n_spaces -= output_tab_width; 526 } 527 } 528 while (n_spaces-- > 0) 529 putchar(' '); 530 } 531 532 /* Output a single word, or add it to the buffer. 533 * indent0 and indent1 are the indents to use on the first and subsequent 534 * lines of a paragraph. They'll often be the same, of course. 535 */ 536 static void 537 output_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces) 538 { 539 size_t new_x = x + pending_spaces + length; 540 size_t indent = output_in_paragraph ? indent1 : indent0; 541 542 /* If either |spaces==0| (at end of line) or |coalesce_spaces_P| 543 * (squashing internal whitespace), then add just one space; 544 * except that if the last character was a sentence-ender we 545 * actually add two spaces. 546 */ 547 if (coalesce_spaces_P || spaces == 0) 548 spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1; 549 550 if (new_x <= goal_length) { 551 /* After adding the word we still aren't at the goal length, 552 * so clearly we add it to the buffer rather than outputing it. 553 */ 554 memset(output_buffer+x0, ' ', pending_spaces); 555 x0 += pending_spaces; 556 x += pending_spaces; 557 memcpy(output_buffer+x0, word, length); 558 x0 += length; 559 x += length; 560 pending_spaces = spaces; 561 } else { 562 /* Adding the word takes us past the goal. Print the line-so-far, 563 * and the word too iff either (1) the lsf is empty or (2) that 564 * makes us nearer the goal but doesn't take us over the limit, 565 * or (3) the word on its own takes us over the limit. 566 * In case (3) we put a newline in between. 567 */ 568 if (indent > 0) 569 output_indent(indent); 570 fwrite(output_buffer, 1, x0, stdout); 571 if (x0 == 0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) { 572 printf("%*s", (int)pending_spaces, ""); 573 goto write_out_word; 574 } else { 575 /* If the word takes us over the limit on its own, just 576 * spit it out and don't bother buffering it. 577 */ 578 if (indent+length > max_length) { 579 putchar('\n'); 580 if (indent > 0) 581 output_indent(indent); 582 write_out_word: 583 fwrite(word, 1, length, stdout); 584 x0 = 0; 585 x = indent1; 586 pending_spaces = 0; 587 } else { 588 memcpy(output_buffer, word, length); 589 x0 = length; 590 x = length+indent1; 591 pending_spaces = spaces; 592 } 593 } 594 595 putchar('\n'); 596 output_in_paragraph = 1; 597 } 598 } 599 600 /* Process a stream, but just center its lines rather than trying to 601 * format them neatly. 602 */ 603 static void 604 center_stream(FILE *stream, const char *name) 605 { 606 char *line; 607 size_t length; 608 size_t l; 609 610 while ((line = get_line(stream, &length)) != 0) { 611 l = length; 612 while (l > 0 && isspace(*line)) { 613 ++line; 614 --l; 615 } 616 617 length = l; 618 619 while (l < goal_length) { 620 putchar(' '); 621 l += 2; 622 } 623 624 fwrite(line, 1, length, stdout); 625 putchar('\n'); 626 } 627 628 if (ferror(stream)) { 629 warn("%s", name); 630 ++n_errors; 631 } 632 } 633 634 /* Get a single line from a stream. Expand tabs, strip control 635 * characters and trailing whitespace, and handle backspaces. 636 * Return the address of the buffer containing the line, and 637 * put the length of the line in |lengthp|. 638 * This can cope with arbitrarily long lines, and with lines 639 * without terminating \n. 640 * If there are no characters left or an error happens, we 641 * return 0. 642 * Don't confuse |spaces_pending| here with the global 643 * |pending_spaces|. 644 */ 645 static char * 646 get_line(FILE *stream, size_t *lengthp) 647 { 648 int ch; 649 int troff = 0; 650 static char *buf = NULL; 651 static size_t length = 0; 652 size_t len = 0; 653 size_t spaces_pending = 0; 654 655 if (buf == NULL) { 656 length = 100; 657 buf = XMALLOC(length); 658 } 659 660 while ((ch = getc(stream)) != '\n' && ch != EOF) { 661 if ((len + spaces_pending == 0) && (ch == '.' && !format_troff)) 662 troff = 1; 663 if (ch == ' ') { 664 ++spaces_pending; 665 } else if (troff || !iscntrl(ch)) { 666 while (len + spaces_pending >= length) { 667 length *= 2; 668 buf = xrealloc(buf, length); 669 } 670 671 while (spaces_pending > 0) { 672 --spaces_pending; 673 buf[len++] = ' '; 674 } 675 buf[len++] = ch; 676 } else if (ch == '\t') { 677 spaces_pending += tab_width - (len+spaces_pending)%tab_width; 678 } else if (ch == '\b') { 679 if (len) 680 --len; 681 } 682 } 683 684 *lengthp = len; 685 return (len > 0 || ch != EOF) ? buf : 0; 686 } 687 688 /* (Re)allocate some memory, exiting with an error if we can't. 689 */ 690 static void * 691 xrealloc(void *ptr, size_t nbytes) 692 { 693 void *p; 694 695 p = realloc(ptr, nbytes); 696 if (p == NULL) 697 errx(EX_OSERR, "out of memory"); 698 return p; 699 } 700 701 void 702 usage(void) 703 { 704 extern char *__progname; 705 706 fprintf(stderr, 707 "usage: %s [-cmnps] [-d chars] [-l number] [-t number]\n" 708 "\t[goal [maximum] | -width | -w width] [file ...]\n", 709 __progname); 710 exit (1); 711 } 712