1 /* $OpenBSD: fmt.c,v 1.19 2001/11/29 00:33:06 millert 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 #ifndef lint 172 static const char rcsid[] = 173 "$OpenBSD: fmt.c,v 1.19 2001/11/29 00:33:06 millert Exp $"; 174 static const char copyright[] = 175 "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n"; 176 #endif /* not lint */ 177 178 #include <ctype.h> 179 #include <err.h> 180 #include <locale.h> 181 #include <stdio.h> 182 #include <stdlib.h> 183 #include <string.h> 184 #include <sysexits.h> 185 #include <unistd.h> 186 187 /* Something that, we hope, will never be a genuine line length, 188 * indentation etc. 189 */ 190 #define SILLY ((size_t)-1) 191 192 /* I used to use |strtoul| for this, but (1) not all systems have it 193 * and (2) it's probably better to use |strtol| to detect negative 194 * numbers better. 195 * If |fussyp==0| then we don't complain about non-numbers 196 * (returning 0 instead), but we do complain about bad numbers. 197 */ 198 static size_t 199 get_positive(const char *s, const char *err_mess, int fussyP) { 200 char *t; 201 long result = strtol(s,&t,0); 202 if (*t) { if (fussyP) goto Lose; else return 0; } 203 if (result<=0) { Lose: errx(EX_USAGE, err_mess); } 204 return (size_t) result; 205 } 206 207 /* Global variables */ 208 209 static int centerP=0; /* Try to center lines? */ 210 static size_t goal_length=0; /* Target length for output lines */ 211 static size_t max_length=0; /* Maximum length for output lines */ 212 static int coalesce_spaces_P=0; /* Coalesce multiple whitespace -> ' ' ? */ 213 static int allow_indented_paragraphs=0; /* Can first line have diff. ind.? */ 214 static int tab_width=8; /* Number of spaces per tab stop */ 215 static size_t output_tab_width=0; /* Ditto, when squashing leading spaces */ 216 static const char *sentence_enders=".?!"; /* Double-space after these */ 217 static int grok_mail_headers=0; /* treat embedded mail headers magically? */ 218 static int format_troff=0; /* Format troff? */ 219 220 static int n_errors=0; /* Number of failed files. Return on exit. */ 221 static char *output_buffer=0; /* Output line will be built here */ 222 static size_t x; /* Horizontal position in output line */ 223 static size_t x0; /* Ditto, ignoring leading whitespace */ 224 static size_t pending_spaces; /* Spaces to add before next word */ 225 static int output_in_paragraph=0; /* Any of current para written out yet? */ 226 227 /* Prototypes */ 228 229 static void process_named_file(const char *); 230 static void process_stream(FILE *, const char *); 231 static size_t indent_length(const char *, size_t); 232 static int might_be_header(const unsigned char *); 233 static void new_paragraph(size_t, size_t); 234 static void output_word(size_t, size_t, const char *, size_t, size_t); 235 static void output_indent(size_t); 236 static void center_stream(FILE *, const char *); 237 static char * get_line(FILE *, size_t *); 238 static void * xrealloc(void *, size_t); 239 240 #define XMALLOC(x) xrealloc(0,x) 241 242 /* Here is perhaps the right place to mention that this code is 243 * all in top-down order. Hence, |main| comes first. 244 */ 245 int 246 main(int argc, char *argv[]) { 247 int ch; /* used for |getopt| processing */ 248 249 250 (void)setlocale(LC_CTYPE, ""); 251 252 /* 1. Grok parameters. */ 253 254 while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) 255 switch(ch) { 256 case 'c': 257 centerP = 1; 258 continue; 259 case 'd': 260 sentence_enders = optarg; 261 continue; 262 case 'l': 263 output_tab_width 264 = get_positive(optarg, "output tab width must be positive", 1); 265 continue; 266 case 'm': 267 grok_mail_headers = 1; 268 continue; 269 case 'n': 270 format_troff = 1; 271 continue; 272 case 'p': 273 allow_indented_paragraphs = 1; 274 continue; 275 case 's': 276 coalesce_spaces_P = 1; 277 continue; 278 case 't': 279 tab_width = get_positive(optarg, "tab width must be positive", 1); 280 continue; 281 case 'w': 282 goal_length = get_positive(optarg, "width must be positive", 1); 283 max_length = goal_length; 284 continue; 285 case '0': case '1': case '2': case '3': case '4': case '5': 286 case '6': case '7': case '8': case '9': 287 /* XXX this is not a stylistically approved use of getopt() */ 288 if (goal_length==0) { 289 char *p; 290 p = argv[optind - 1]; 291 if (p[0] == '-' && p[1] == ch && !p[2]) 292 goal_length = get_positive(++p, "width must be nonzero", 1); 293 else 294 goal_length = get_positive(argv[optind]+1, 295 "width must be nonzero", 1); 296 max_length = goal_length; 297 } 298 continue; 299 case 'h': default: 300 fprintf(stderr, 301 "Usage: fmt [-cmps] [-d chars] [-l num] [-t num]\n" 302 " [-w width | -width | goal [maximum]] [file ...]\n" 303 "Options: -c center each line instead of formatting\n" 304 " -d <chars> double-space after <chars> at line end\n" 305 " -l <n> turn each <n> spaces at start of line into a tab\n" 306 " -m try to make sure mail header lines stay separate\n" 307 " -n format lines beginning with a dot\n" 308 " -p allow indented paragraphs\n" 309 " -s coalesce whitespace inside lines\n" 310 " -t <n> have tabs every <n> columns\n" 311 " -w <n> set maximum width to <n>\n" 312 " goal set target width to goal\n"); 313 exit(ch=='h' ? 0 : EX_USAGE); 314 } 315 argc -= optind; argv += optind; 316 317 /* [ goal [ maximum ] ] */ 318 319 if (argc>0 && goal_length==0 320 && (goal_length=get_positive(*argv,"goal length must be positive", 0)) 321 != 0) { 322 --argc; ++argv; 323 if (argc>0 324 && (max_length=get_positive(*argv,"max length must be positive", 0)) 325 != 0) { 326 --argc; ++argv; 327 if (max_length<goal_length) 328 errx(EX_USAGE, "max length must be >= goal length"); 329 } 330 } 331 if (goal_length==0) goal_length = 65; 332 if (max_length==0) max_length = goal_length+10; 333 output_buffer = XMALLOC(max_length+1); /* really needn't be longer */ 334 335 /* 2. Process files. */ 336 337 if (argc>0) { 338 while (argc-->0) process_named_file(*argv++); 339 } 340 else { 341 process_stream(stdin, "standard input"); 342 } 343 344 /* We're done. */ 345 346 return n_errors ? EX_NOINPUT : 0; 347 348 } 349 350 /* Process a single file, given its name. 351 */ 352 static void 353 process_named_file(const char *name) { 354 FILE *f=fopen(name, "r"); 355 if (!f) { perror(name); ++n_errors; } 356 else { 357 process_stream(f, name); 358 fclose(f); 359 } 360 } 361 362 /* Types of mail header continuation lines: 363 */ 364 typedef enum { 365 hdr_ParagraphStart = -1, 366 hdr_NonHeader = 0, 367 hdr_Header = 1, 368 hdr_Continuation = 2 369 } HdrType; 370 371 /* Process a stream. This is where the real work happens, 372 * except that centering is handled separately. 373 */ 374 static void 375 process_stream(FILE *stream, const char *name) { 376 size_t last_indent=SILLY; /* how many spaces in last indent? */ 377 size_t para_line_number=0; /* how many lines already read in this para? */ 378 size_t first_indent=SILLY; /* indentation of line 0 of paragraph */ 379 HdrType prev_header_type=hdr_ParagraphStart; 380 /* ^-- header_type of previous line; -1 at para start */ 381 char *line; 382 size_t length; 383 384 if (centerP) { center_stream(stream, name); return; } 385 while ((line=get_line(stream,&length)) != NULL) { 386 size_t np=indent_length(line, length); 387 { HdrType header_type=hdr_NonHeader; 388 if (grok_mail_headers && prev_header_type!=hdr_NonHeader) { 389 if (np==0 && might_be_header(line)) 390 header_type = hdr_Header; 391 else if (np>0 && prev_header_type>hdr_NonHeader) 392 header_type = hdr_Continuation; 393 } 394 /* We need a new paragraph if and only if: 395 * this line is blank, 396 * OR it's a troff request, 397 * OR it's a mail header, 398 * OR it's not a mail header AND the last line was one, 399 * OR the indentation has changed 400 * AND the line isn't a mail header continuation line 401 * AND this isn't the second line of an indented paragraph. 402 */ 403 if ( length==0 404 || (line[0]=='.' && !format_troff) 405 || header_type==hdr_Header 406 || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader) 407 || (np!=last_indent 408 && header_type != hdr_Continuation 409 && (!allow_indented_paragraphs || para_line_number != 1)) ) { 410 new_paragraph(output_in_paragraph ? last_indent : first_indent, np); 411 para_line_number = 0; 412 first_indent = np; 413 last_indent = np; 414 /* nroff compatibility */ 415 if (length>0 && line[0]=='.' && !format_troff) { 416 printf("%.*s\n", (int)length, line); 417 continue; 418 } 419 if (header_type==hdr_Header) last_indent=2; /* for cont. lines */ 420 if (length==0) { 421 putchar('\n'); 422 prev_header_type=hdr_ParagraphStart; 423 continue; 424 } 425 } 426 else { 427 /* If this is an indented paragraph other than a mail header 428 * continuation, set |last_indent|. 429 */ 430 if (np != last_indent && header_type != hdr_Continuation) 431 last_indent=np; 432 } 433 prev_header_type = header_type; 434 } 435 436 { size_t n=np; 437 while (n<length) { 438 /* Find word end and count spaces after it */ 439 size_t word_length=0, space_length=0; 440 while (n+word_length < length && line[n+word_length] != ' ') 441 ++word_length; 442 space_length = word_length; 443 while (n+space_length < length && line[n+space_length] == ' ') 444 ++space_length; 445 /* Send the word to the output machinery. */ 446 output_word(first_indent, last_indent, 447 line+n, word_length, space_length-word_length); 448 n += space_length; 449 } 450 } 451 ++para_line_number; 452 } 453 new_paragraph(output_in_paragraph ? last_indent : first_indent, 0); 454 if (ferror(stream)) { perror(name); ++n_errors; } 455 } 456 457 /* How long is the indent on this line? 458 */ 459 static size_t 460 indent_length(const char *line, size_t length) { 461 size_t n=0; 462 while (n<length && *line++ == ' ') ++n; 463 return n; 464 } 465 466 /* Might this line be a mail header? 467 * We deem a line to be a possible header if it matches the 468 * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same 469 * as in RFC whatever-number-it-is; we want to be gratuitously 470 * conservative to avoid mangling ordinary civilised text. 471 */ 472 static int 473 might_be_header(const unsigned char *line) { 474 if (!isupper(*line++)) return 0; 475 while (*line && (isalnum(*line) || *line=='-')) ++line; 476 return (*line==':' && isspace(line[1])); 477 } 478 479 /* Begin a new paragraph with an indent of |indent| spaces. 480 */ 481 static void 482 new_paragraph(size_t old_indent, size_t indent) { 483 if (x0) { 484 if (old_indent>0) output_indent(old_indent); 485 fwrite(output_buffer, 1, x0, stdout); 486 putchar('\n'); 487 } 488 x=indent; x0=0; pending_spaces=0; 489 output_in_paragraph = 0; 490 } 491 492 /* Output spaces or tabs for leading indentation. 493 */ 494 static void 495 output_indent(size_t n_spaces) { 496 if (output_tab_width) { 497 while (n_spaces >= output_tab_width) { 498 putchar('\t'); 499 n_spaces -= output_tab_width; 500 } 501 } 502 while (n_spaces-- > 0) putchar(' '); 503 } 504 505 /* Output a single word, or add it to the buffer. 506 * indent0 and indent1 are the indents to use on the first and subsequent 507 * lines of a paragraph. They'll often be the same, of course. 508 */ 509 static void 510 output_word(size_t indent0, size_t indent1, const char *word, size_t length, size_t spaces) { 511 size_t new_x = x+pending_spaces+length; 512 size_t indent = output_in_paragraph ? indent1 : indent0; 513 514 /* If either |spaces==0| (at end of line) or |coalesce_spaces_P| 515 * (squashing internal whitespace), then add just one space; 516 * except that if the last character was a sentence-ender we 517 * actually add two spaces. 518 */ 519 if (coalesce_spaces_P || spaces==0) 520 spaces = strchr(sentence_enders, word[length-1]) ? 2 : 1; 521 522 if (new_x<=goal_length) { 523 /* After adding the word we still aren't at the goal length, 524 * so clearly we add it to the buffer rather than outputing it. 525 */ 526 memset(output_buffer+x0, ' ', pending_spaces); 527 x0 += pending_spaces; x += pending_spaces; 528 memcpy(output_buffer+x0, word, length); 529 x0 += length; x += length; 530 pending_spaces = spaces; 531 } 532 else { 533 /* Adding the word takes us past the goal. Print the line-so-far, 534 * and the word too iff either (1) the lsf is empty or (2) that 535 * makes us nearer the goal but doesn't take us over the limit, 536 * or (3) the word on its own takes us over the limit. 537 * In case (3) we put a newline in between. 538 */ 539 if (indent>0) output_indent(indent); 540 fwrite(output_buffer, 1, x0, stdout); 541 if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) { 542 printf("%*s", (int)pending_spaces, ""); 543 goto write_out_word; 544 } 545 else { 546 /* If the word takes us over the limit on its own, just 547 * spit it out and don't bother buffering it. 548 */ 549 if (indent+length > max_length) { 550 putchar('\n'); 551 if (indent>0) output_indent(indent); 552 write_out_word: 553 fwrite(word, 1, length, stdout); 554 x0 = 0; x = indent1; pending_spaces = 0; 555 } 556 else { 557 memcpy(output_buffer, word, length); 558 x0 = length; x = length+indent1; pending_spaces = spaces; 559 } 560 } 561 putchar('\n'); 562 output_in_paragraph = 1; 563 } 564 } 565 566 /* Process a stream, but just center its lines rather than trying to 567 * format them neatly. 568 */ 569 static void 570 center_stream(FILE *stream, const char *name) { 571 char *line; 572 size_t length; 573 while ((line=get_line(stream, &length)) != 0) { 574 size_t l=length; 575 while (l>0 && isspace(*line)) { ++line; --l; } 576 length=l; 577 while (l<goal_length) { putchar(' '); l+=2; } 578 fwrite(line, 1, length, stdout); 579 putchar('\n'); 580 } 581 if (ferror(stream)) { perror(name); ++n_errors; } 582 } 583 584 /* Get a single line from a stream. Expand tabs, strip control 585 * characters and trailing whitespace, and handle backspaces. 586 * Return the address of the buffer containing the line, and 587 * put the length of the line in |lengthp|. 588 * This can cope with arbitrarily long lines, and with lines 589 * without terminating \n. 590 * If there are no characters left or an error happens, we 591 * return 0. 592 * Don't confuse |spaces_pending| here with the global 593 * |pending_spaces|. 594 */ 595 static char * 596 get_line(FILE *stream, size_t *lengthp) { 597 static char *buf=NULL; 598 static size_t length=0; 599 size_t len=0; 600 int ch; 601 size_t spaces_pending=0; 602 int troff=0; 603 604 if (buf==NULL) { length=100; buf=XMALLOC(length); } 605 while ((ch=getc(stream)) != '\n' && ch != EOF) { 606 if (len+spaces_pending==0 && ch=='.' && !format_troff) troff=1; 607 if (ch==' ') ++spaces_pending; 608 else if (troff || !iscntrl(ch)) { 609 while (len+spaces_pending >= length) { 610 length*=2; buf=xrealloc(buf, length); 611 } 612 while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; } 613 buf[len++] = ch; 614 } 615 else if (ch=='\t') 616 spaces_pending += tab_width - (len+spaces_pending)%tab_width; 617 else if (ch=='\b') { if (len) --len; } 618 } 619 *lengthp=len; 620 return (len>0 || ch!=EOF) ? buf : 0; 621 } 622 623 /* (Re)allocate some memory, exiting with an error if we can't. 624 */ 625 static void * 626 xrealloc(void *ptr, size_t nbytes) { 627 void *p = realloc(ptr, nbytes); 628 if (p == NULL) errx(EX_OSERR, "out of memory"); 629 return p; 630 } 631