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