fmt.c revision 133008
177807Sru/* $OpenBSD: fmt.c,v 1.16 2000/06/25 15:35:42 pjanzen Exp $ */ 277807Sru 377807Sru/* Sensible version of fmt 41590Srgrimes * 577807Sru * Syntax: fmt [ options ] [ goal [ max ] ] [ filename ... ] 677807Sru * 777807Sru * Since the documentation for the original fmt is so poor, here 877807Sru * is an accurate description of what this one does. It's usually 977807Sru * the same. The *mechanism* used may differ from that suggested 1077807Sru * here. Note that we are *not* entirely compatible with fmt, 1177807Sru * because fmt gets so many things wrong. 1277807Sru * 1377807Sru * 1. Tabs are expanded, assuming 8-space tab stops. 1477807Sru * If the `-t <n>' option is given, we assume <n>-space 1577807Sru * tab stops instead. 1677807Sru * Trailing blanks are removed from all lines. 1777807Sru * x\b == nothing, for any x other than \b. 1877807Sru * Other control characters are simply stripped. This 1977807Sru * includes \r. 2077807Sru * 2. Each line is split into leading whitespace and 2177807Sru * everything else. Maximal consecutive sequences of 2277807Sru * lines with the same leading whitespace are considered 2377807Sru * to form paragraphs, except that a blank line is always 2477807Sru * a paragraph to itself. 2577807Sru * If the `-p' option is given then the first line of a 2677807Sru * paragraph is permitted to have indentation different 2777807Sru * from that of the other lines. 2877807Sru * If the `-m' option is given then a line that looks 2977807Sru * like a mail message header, if it is not immediately 3077807Sru * preceded by a non-blank non-message-header line, is 3177807Sru * taken to start a new paragraph, which also contains 3277807Sru * any subsequent lines with non-empty leading whitespace. 3389268Sru * Unless the `-n' option is given, lines beginning with 3489268Sru * a . (dot) are not formatted. 3577807Sru * 3. The "everything else" is split into words; a word 3677807Sru * includes its trailing whitespace, and a word at the 3777807Sru * end of a line is deemed to be followed by a single 3877807Sru * space, or two spaces if it ends with a sentence-end 3977807Sru * character. (See the `-d' option for how to change that.) 4077807Sru * If the `-s' option has been given, then a word's trailing 4177807Sru * whitespace is replaced by what it would have had if it 4277807Sru * had occurred at end of line. 4377807Sru * 4. Each paragraph is sent to standard output as follows. 4477807Sru * We output the leading whitespace, and then enough words 4577807Sru * to make the line length as near as possible to the goal 4677807Sru * without exceeding the maximum. (If a single word would 4777807Sru * exceed the maximum, we output that anyway.) Of course 4877807Sru * the trailing whitespace of the last word is ignored. 4977807Sru * We then emit a newline and start again if there are any 5077807Sru * words left. 5177807Sru * Note that for a blank line this translates as "We emit 5277807Sru * a newline". 5377807Sru * If the `-l <n>' option is given, then leading whitespace 5477807Sru * is modified slightly: <n> spaces are replaced by a tab. 5577807Sru * Indented paragraphs (see above under `-p') make matters 5677807Sru * more complicated than this suggests. Actually every paragraph 5777807Sru * has two `leading whitespace' values; the value for the first 5877807Sru * line, and the value for the most recent line. (While processing 5977807Sru * the first line, the two are equal. When `-p' has not been 6077807Sru * given, they are always equal.) The leading whitespace 6177807Sru * actually output is that of the first line (for the first 6277807Sru * line of *output*) or that of the most recent line (for 6377807Sru * all other lines of output). 6477807Sru * When `-m' has been given, message header paragraphs are 6577807Sru * taken as having first-leading-whitespace empty and 6677807Sru * subsequent-leading-whitespace two spaces. 6777807Sru * 6877807Sru * Multiple input files are formatted one at a time, so that a file 6977807Sru * never ends in the middle of a line. 7077807Sru * 7177807Sru * There's an alternative mode of operation, invoked by giving 7277807Sru * the `-c' option. In that case we just center every line, 7377807Sru * and most of the other options are ignored. This should 7477807Sru * really be in a separate program, but we must stay compatible 7577807Sru * with old `fmt'. 7677807Sru * 7777807Sru * QUERY: Should `-m' also try to do the right thing with quoted text? 7877807Sru * QUERY: `-b' to treat backslashed whitespace as old `fmt' does? 7977807Sru * QUERY: Option meaning `never join lines'? 8077807Sru * QUERY: Option meaning `split in mid-word to avoid overlong lines'? 8177807Sru * (Those last two might not be useful, since we have `fold'.) 8277807Sru * 8377807Sru * Differences from old `fmt': 8477807Sru * 8577807Sru * - We have many more options. Options that aren't understood 8677807Sru * generate a lengthy usage message, rather than being 8777807Sru * treated as filenames. 8877807Sru * - Even with `-m', our handling of message headers is 8977807Sru * significantly different. (And much better.) 9077807Sru * - We don't treat `\ ' as non-word-breaking. 9177807Sru * - Downward changes of indentation start new paragraphs 9277807Sru * for us, as well as upward. (I think old `fmt' behaves 9377807Sru * in the way it does in order to allow indented paragraphs, 9477807Sru * but this is a broken way of making indented paragraphs 9577807Sru * behave right.) 9677807Sru * - Given the choice of going over or under |goal_length| 9777807Sru * by the same amount, we go over; old `fmt' goes under. 9877807Sru * - We treat `?' as ending a sentence, and not `:'. Old `fmt' 9977807Sru * does the reverse. 10077807Sru * - We return approved return codes. Old `fmt' returns 10177807Sru * 1 for some errors, and *the number of unopenable files* 10277807Sru * when that was all that went wrong. 10377807Sru * - We have fewer crashes and more helpful error messages. 10477807Sru * - We don't turn spaces into tabs at starts of lines unless 10577807Sru * specifically requested. 10677807Sru * - New `fmt' is somewhat smaller and slightly faster than 10777807Sru * old `fmt'. 10877807Sru * 10977807Sru * Bugs: 11077807Sru * 11177807Sru * None known. There probably are some, though. 11277807Sru * 11377807Sru * Portability: 11477807Sru * 11577807Sru * I believe this code to be pretty portable. It does require 11677807Sru * that you have `getopt'. If you need to include "getopt.h" 11777807Sru * for this (e.g., if your system didn't come with `getopt' 11877807Sru * and you installed it yourself) then you should arrange for 11977807Sru * NEED_getopt_h to be #defined. 12077807Sru * 12177807Sru * Everything here should work OK even on nasty 16-bit 12277807Sru * machines and nice 64-bit ones. However, it's only really 12377807Sru * been tested on my FreeBSD machine. Your mileage may vary. 12477807Sru */ 12577807Sru 12677807Sru/* Copyright (c) 1997 Gareth McCaughan. All rights reserved. 12777807Sru * 12877807Sru * Redistribution and use of this code, in source or binary forms, 12977807Sru * with or without modification, are permitted subject to the following 13077807Sru * conditions: 13177807Sru * 13277807Sru * - Redistribution of source code must retain the above copyright 1331590Srgrimes * notice, this list of conditions and the following disclaimer. 1341590Srgrimes * 13577807Sru * - If you distribute modified source code it must also include 13677807Sru * a notice saying that it has been modified, and giving a brief 13777807Sru * description of what changes have been made. 13877807Sru * 13977807Sru * Disclaimer: I am not responsible for the results of using this code. 14077807Sru * If it formats your hard disc, sends obscene messages to 14177807Sru * your boss and kills your children then that's your problem 14277807Sru * not mine. I give absolutely no warranty of any sort as to 14377807Sru * what the program will do, and absolutely refuse to be held 14477807Sru * liable for any consequences of your using it. 14577807Sru * Thank you. Have a nice day. 1461590Srgrimes */ 1471590Srgrimes 14877807Sru/* RCS change log: 14977807Sru * Revision 1.5 1998/03/02 18:02:21 gjm11 15077807Sru * Minor changes for portability. 15177807Sru * 15277807Sru * Revision 1.4 1997/10/01 11:51:28 gjm11 15377807Sru * Repair broken indented-paragraph handling. 15477807Sru * Add mail message header stuff. 15577807Sru * Improve comments and layout. 15677807Sru * Make usable with non-BSD systems. 15777807Sru * Add revision display to usage message. 15877807Sru * 15977807Sru * Revision 1.3 1997/09/30 16:24:47 gjm11 16077807Sru * Add copyright notice, rcsid string and log message. 16177807Sru * 16277807Sru * Revision 1.2 1997/09/30 16:13:39 gjm11 16377807Sru * Add options: -d <chars>, -l <width>, -p, -s, -t <width>, -h . 16477807Sru * Parse options with `getopt'. Clean up code generally. 16577807Sru * Make comments more accurate. 16677807Sru * 16777807Sru * Revision 1.1 1997/09/30 11:29:57 gjm11 16877807Sru * Initial revision 16977807Sru */ 1701590Srgrimes 1711590Srgrimes#ifndef lint 17277807Srustatic const char copyright[] = 17377807Sru "Copyright (c) 1997 Gareth McCaughan. All rights reserved.\n"; 1741590Srgrimes#endif /* not lint */ 17599112Sobrien#include <sys/cdefs.h> 17699112Sobrien__FBSDID("$FreeBSD: head/usr.bin/fmt/fmt.c 133008 2004-08-02 11:10:20Z tjr $"); 1771590Srgrimes 17827185Scharnier#include <err.h> 17911765Sache#include <locale.h> 18027185Scharnier#include <stdio.h> 18112317Sjoerg#include <stdlib.h> 18227185Scharnier#include <string.h> 18377807Sru#include <sysexits.h> 18477807Sru#include <unistd.h> 185133008Stjr#include <wchar.h> 186133008Stjr#include <wctype.h> 1871590Srgrimes 18877807Sru/* Something that, we hope, will never be a genuine line length, 18977807Sru * indentation etc. 1901590Srgrimes */ 19177807Sru#define SILLY ((size_t)-1) 1921590Srgrimes 19377807Sru/* I used to use |strtoul| for this, but (1) not all systems have it 19477807Sru * and (2) it's probably better to use |strtol| to detect negative 19577807Sru * numbers better. 19677807Sru * If |fussyp==0| then we don't complain about non-numbers 19777807Sru * (returning 0 instead), but we do complain about bad numbers. 1981590Srgrimes */ 19977807Srustatic size_t 20077807Sruget_positive(const char *s, const char *err_mess, int fussyP) { 20177807Sru char *t; 20277807Sru long result = strtol(s,&t,0); 20377807Sru if (*t) { if (fussyP) goto Lose; else return 0; } 20481510Skris if (result<=0) { Lose: errx(EX_USAGE, "%s", err_mess); } 20577807Sru return (size_t) result; 20677807Sru} 2071590Srgrimes 20881701Srustatic size_t 20981701Sruget_nonnegative(const char *s, const char *err_mess, int fussyP) { 21081701Sru char *t; 21181701Sru long result = strtol(s,&t,0); 21281701Sru if (*t) { if (fussyP) goto Lose; else return 0; } 21381701Sru if (result<0) { Lose: errx(EX_USAGE, "%s", err_mess); } 21481701Sru return (size_t) result; 21581701Sru} 21681701Sru 21777807Sru/* Global variables */ 2181590Srgrimes 21977807Srustatic int centerP=0; /* Try to center lines? */ 22077807Srustatic size_t goal_length=0; /* Target length for output lines */ 22177807Srustatic size_t max_length=0; /* Maximum length for output lines */ 22277807Srustatic int coalesce_spaces_P=0; /* Coalesce multiple whitespace -> ' ' ? */ 22377807Srustatic int allow_indented_paragraphs=0; /* Can first line have diff. ind.? */ 22477807Srustatic int tab_width=8; /* Number of spaces per tab stop */ 22581701Srustatic size_t output_tab_width=8; /* Ditto, when squashing leading spaces */ 226133008Stjrstatic const wchar_t *sentence_enders=L".?!"; /* Double-space after these */ 22777807Srustatic int grok_mail_headers=0; /* treat embedded mail headers magically? */ 22889268Srustatic int format_troff=0; /* Format troff? */ 2291590Srgrimes 23077807Srustatic int n_errors=0; /* Number of failed files. Return on exit. */ 231133008Stjrstatic wchar_t *output_buffer=0; /* Output line will be built here */ 23277807Srustatic size_t x; /* Horizontal position in output line */ 23377807Srustatic size_t x0; /* Ditto, ignoring leading whitespace */ 234133008Stjrstatic size_t output_buffer_length = 0; 23577807Srustatic size_t pending_spaces; /* Spaces to add before next word */ 23677807Srustatic int output_in_paragraph=0; /* Any of current para written out yet? */ 23727185Scharnier 23877807Sru/* Prototypes */ 23977807Sru 24077807Srustatic void process_named_file (const char *); 24177807Srustatic void process_stream (FILE *, const char *); 242133008Stjrstatic size_t indent_length (const wchar_t *, size_t); 243133008Stjrstatic int might_be_header (const wchar_t *); 24477807Srustatic void new_paragraph (size_t, size_t); 245133008Stjrstatic void output_word (size_t, size_t, const wchar_t *, size_t, 246133008Stjr size_t); 24777807Srustatic void output_indent (size_t); 24877807Srustatic void center_stream (FILE *, const char *); 249133008Stjrstatic wchar_t * get_line (FILE *, size_t *); 25077807Srustatic void * xrealloc (void *, size_t); 25177807Sru 25277807Sru#define XMALLOC(x) xrealloc(0,x) 25377807Sru 25477807Sru/* Here is perhaps the right place to mention that this code is 25577807Sru * all in top-down order. Hence, |main| comes first. 2561590Srgrimes */ 25727185Scharnierint 25877807Srumain(int argc, char *argv[]) { 25977807Sru int ch; /* used for |getopt| processing */ 260133008Stjr wchar_t *tmp; 261133008Stjr size_t len; 262133008Stjr const char *src; 2631590Srgrimes 26477807Sru (void) setlocale(LC_CTYPE, ""); 2651590Srgrimes 26677807Sru /* 1. Grok parameters. */ 2671590Srgrimes 26889268Sru while ((ch = getopt(argc, argv, "0123456789cd:hl:mnpst:w:")) != -1) 26977807Sru switch(ch) { 27077807Sru case 'c': 27177807Sru centerP = 1; 27289268Sru format_troff = 1; 27377807Sru continue; 27477807Sru case 'd': 275133008Stjr src = optarg; 276133008Stjr len = mbsrtowcs(NULL, &src, 0, NULL); 277133008Stjr if (len == (size_t)-1) 278133008Stjr err(EX_USAGE, "bad sentence-ending character set"); 279133008Stjr tmp = XMALLOC((len + 1) * sizeof(wchar_t)); 280133008Stjr mbsrtowcs(tmp, &src, len + 1, NULL); 281133008Stjr sentence_enders = tmp; 28277807Sru continue; 28377807Sru case 'l': 28477807Sru output_tab_width 28581701Sru = get_nonnegative(optarg, "output tab width must be non-negative", 1); 28677807Sru continue; 28777807Sru case 'm': 28877807Sru grok_mail_headers = 1; 28977807Sru continue; 29089268Sru case 'n': 29189268Sru format_troff = 1; 29289268Sru continue; 29377807Sru case 'p': 29477807Sru allow_indented_paragraphs = 1; 29577807Sru continue; 29677807Sru case 's': 29777807Sru coalesce_spaces_P = 1; 29877807Sru continue; 29977807Sru case 't': 30077807Sru tab_width = get_positive(optarg, "tab width must be positive", 1); 30177807Sru continue; 30277807Sru case 'w': 30377807Sru goal_length = get_positive(optarg, "width must be positive", 1); 30477807Sru max_length = goal_length; 30577807Sru continue; 30677807Sru case '0': case '1': case '2': case '3': case '4': case '5': 30777807Sru case '6': case '7': case '8': case '9': 30877807Sru /* XXX this is not a stylistically approved use of getopt() */ 30977807Sru if (goal_length==0) { 31077807Sru char *p; 31177807Sru p = argv[optind - 1]; 31277807Sru if (p[0] == '-' && p[1] == ch && !p[2]) 31377807Sru goal_length = get_positive(++p, "width must be nonzero", 1); 31477807Sru else 31577807Sru goal_length = get_positive(argv[optind]+1, 31677807Sru "width must be nonzero", 1); 31777807Sru max_length = goal_length; 31877807Sru } 31977807Sru continue; 32077807Sru case 'h': default: 32177807Sru fprintf(stderr, 32295258Sdes"usage: fmt [-cmps] [-d chars] [-l num] [-t num]\n" 32377807Sru" [-w width | -width | goal [maximum]] [file ...]\n" 32477807Sru"Options: -c center each line instead of formatting\n" 32577807Sru" -d <chars> double-space after <chars> at line end\n" 32677807Sru" -l <n> turn each <n> spaces at start of line into a tab\n" 32777807Sru" -m try to make sure mail header lines stay separate\n" 32889268Sru" -n format lines beginning with a dot\n" 32977807Sru" -p allow indented paragraphs\n" 33077807Sru" -s coalesce whitespace inside lines\n" 33177807Sru" -t <n> have tabs every <n> columns\n" 33277807Sru" -w <n> set maximum width to <n>\n" 33377807Sru" goal set target width to goal\n"); 33477807Sru exit(ch=='h' ? 0 : EX_USAGE); 33577807Sru } 33677807Sru argc -= optind; argv += optind; 33728478Sjlemon 33877807Sru /* [ goal [ maximum ] ] */ 3391590Srgrimes 34077807Sru if (argc>0 && goal_length==0 34177807Sru && (goal_length=get_positive(*argv,"goal length must be positive", 0)) 34277807Sru != 0) { 34377807Sru --argc; ++argv; 34477807Sru if (argc>0 34577807Sru && (max_length=get_positive(*argv,"max length must be positive", 0)) 34677807Sru != 0) { 34777807Sru --argc; ++argv; 34877807Sru if (max_length<goal_length) 34977807Sru errx(EX_USAGE, "max length must be >= goal length"); 35077807Sru } 35177807Sru } 35277807Sru if (goal_length==0) goal_length = 65; 35377807Sru if (max_length==0) max_length = goal_length+10; 354133008Stjr /* really needn't be longer */ 355133008Stjr output_buffer = XMALLOC((max_length+1) * sizeof(wchar_t)); 3568874Srgrimes 35777807Sru /* 2. Process files. */ 35815344Ssmpatel 35977807Sru if (argc>0) { 36077807Sru while (argc-->0) process_named_file(*argv++); 36177807Sru } 36277807Sru else { 36377807Sru process_stream(stdin, "standard input"); 36477807Sru } 3651590Srgrimes 36677807Sru /* We're done. */ 36777807Sru 36877807Sru return n_errors ? EX_NOINPUT : 0; 36977807Sru 3701590Srgrimes} 3711590Srgrimes 37277807Sru/* Process a single file, given its name. 3731590Srgrimes */ 37477807Srustatic void 37577807Sruprocess_named_file(const char *name) { 37677807Sru FILE *f=fopen(name, "r"); 377132178Stjr if (!f) { warn("%s", name); ++n_errors; } 37877807Sru else { 37977807Sru process_stream(f, name); 380133008Stjr if (ferror(f)) { warn("%s", name); ++n_errors; } 38177807Sru fclose(f); 38277807Sru } 3831590Srgrimes} 3841590Srgrimes 38577807Sru/* Types of mail header continuation lines: 3861590Srgrimes */ 38777807Srutypedef enum { 38877807Sru hdr_ParagraphStart = -1, 38977807Sru hdr_NonHeader = 0, 39077807Sru hdr_Header = 1, 39177807Sru hdr_Continuation = 2 39277807Sru} HdrType; 3931590Srgrimes 39477807Sru/* Process a stream. This is where the real work happens, 39577807Sru * except that centering is handled separately. 39677807Sru */ 39777807Srustatic void 39877807Sruprocess_stream(FILE *stream, const char *name) { 39977807Sru size_t last_indent=SILLY; /* how many spaces in last indent? */ 40077807Sru size_t para_line_number=0; /* how many lines already read in this para? */ 40177807Sru size_t first_indent=SILLY; /* indentation of line 0 of paragraph */ 40277807Sru HdrType prev_header_type=hdr_ParagraphStart; 40377807Sru /* ^-- header_type of previous line; -1 at para start */ 404133008Stjr wchar_t *line; 40577807Sru size_t length; 40630009Sjoerg 40777807Sru if (centerP) { center_stream(stream, name); return; } 40877807Sru while ((line=get_line(stream,&length)) != NULL) { 40977807Sru size_t np=indent_length(line, length); 41077807Sru { HdrType header_type=hdr_NonHeader; 41177807Sru if (grok_mail_headers && prev_header_type!=hdr_NonHeader) { 41277807Sru if (np==0 && might_be_header(line)) 41377807Sru header_type = hdr_Header; 41477807Sru else if (np>0 && prev_header_type>hdr_NonHeader) 41577807Sru header_type = hdr_Continuation; 41677807Sru } 41777807Sru /* We need a new paragraph if and only if: 41877807Sru * this line is blank, 41989268Sru * OR it's a troff request (and we don't format troff), 42077807Sru * OR it's a mail header, 42177807Sru * OR it's not a mail header AND the last line was one, 42277807Sru * OR the indentation has changed 42377807Sru * AND the line isn't a mail header continuation line 42477807Sru * AND this isn't the second line of an indented paragraph. 42577807Sru */ 42677807Sru if ( length==0 42789268Sru || (line[0]=='.' && !format_troff) 42877807Sru || header_type==hdr_Header 42977807Sru || (header_type==hdr_NonHeader && prev_header_type>hdr_NonHeader) 43077807Sru || (np!=last_indent 43177807Sru && header_type != hdr_Continuation 43277807Sru && (!allow_indented_paragraphs || para_line_number != 1)) ) { 43377807Sru new_paragraph(output_in_paragraph ? last_indent : first_indent, np); 43477807Sru para_line_number = 0; 43577807Sru first_indent = np; 43677807Sru last_indent = np; 43777807Sru if (header_type==hdr_Header) last_indent=2; /* for cont. lines */ 43889268Sru if (length==0 || (line[0]=='.' && !format_troff)) { 43989268Sru if (length==0) 440133008Stjr putwchar('\n'); 44189268Sru else 442133008Stjr wprintf(L"%.*ls\n", (int)length, line); 44377807Sru prev_header_type=hdr_ParagraphStart; 44477807Sru continue; 44577807Sru } 44677807Sru } 44777807Sru else { 44877807Sru /* If this is an indented paragraph other than a mail header 44977807Sru * continuation, set |last_indent|. 45077807Sru */ 45177807Sru if (np != last_indent && header_type != hdr_Continuation) 45277807Sru last_indent=np; 45377807Sru } 45477807Sru prev_header_type = header_type; 45577807Sru } 4561590Srgrimes 45777807Sru { size_t n=np; 45877807Sru while (n<length) { 45977807Sru /* Find word end and count spaces after it */ 46077807Sru size_t word_length=0, space_length=0; 46177807Sru while (n+word_length < length && line[n+word_length] != ' ') 46277807Sru ++word_length; 46377807Sru space_length = word_length; 46477807Sru while (n+space_length < length && line[n+space_length] == ' ') 46577807Sru ++space_length; 46677807Sru /* Send the word to the output machinery. */ 46777807Sru output_word(first_indent, last_indent, 46877807Sru line+n, word_length, space_length-word_length); 46977807Sru n += space_length; 47077807Sru } 47177807Sru } 47277807Sru ++para_line_number; 47377807Sru } 47477807Sru new_paragraph(output_in_paragraph ? last_indent : first_indent, 0); 475132178Stjr if (ferror(stream)) { warn("%s", name); ++n_errors; } 4761590Srgrimes} 4771590Srgrimes 47877807Sru/* How long is the indent on this line? 4791590Srgrimes */ 48077807Srustatic size_t 481133008Stjrindent_length(const wchar_t *line, size_t length) { 48277807Sru size_t n=0; 48377807Sru while (n<length && *line++ == ' ') ++n; 48477807Sru return n; 48577807Sru} 4861590Srgrimes 48777807Sru/* Might this line be a mail header? 48877807Sru * We deem a line to be a possible header if it matches the 48977807Sru * Perl regexp /^[A-Z][-A-Za-z0-9]*:\s/. This is *not* the same 49077807Sru * as in RFC whatever-number-it-is; we want to be gratuitously 49177807Sru * conservative to avoid mangling ordinary civilised text. 4921590Srgrimes */ 49377807Srustatic int 494133008Stjrmight_be_header(const wchar_t *line) { 495133008Stjr if (!iswupper(*line++)) return 0; 496133008Stjr while (*line && (iswalnum(*line) || *line=='-')) ++line; 497133008Stjr return (*line==':' && iswspace(line[1])); 4981590Srgrimes} 4991590Srgrimes 50077807Sru/* Begin a new paragraph with an indent of |indent| spaces. 5011590Srgrimes */ 50277807Srustatic void 50377807Srunew_paragraph(size_t old_indent, size_t indent) { 504133008Stjr if (output_buffer_length) { 50577807Sru if (old_indent>0) output_indent(old_indent); 506133008Stjr wprintf(L"%.*ls\n", (int)output_buffer_length, output_buffer); 50777807Sru } 508133008Stjr x=indent; x0=0; output_buffer_length=0; pending_spaces=0; 50977807Sru output_in_paragraph = 0; 5101590Srgrimes} 5111590Srgrimes 51277807Sru/* Output spaces or tabs for leading indentation. 5131590Srgrimes */ 51477807Srustatic void 51577807Sruoutput_indent(size_t n_spaces) { 51677807Sru if (output_tab_width) { 51777807Sru while (n_spaces >= output_tab_width) { 518133008Stjr putwchar('\t'); 51977807Sru n_spaces -= output_tab_width; 52077807Sru } 52177807Sru } 522133008Stjr while (n_spaces-- > 0) putwchar(' '); 5231590Srgrimes} 5241590Srgrimes 52577807Sru/* Output a single word, or add it to the buffer. 52677807Sru * indent0 and indent1 are the indents to use on the first and subsequent 52777807Sru * lines of a paragraph. They'll often be the same, of course. 5281590Srgrimes */ 52977807Srustatic void 530133008Stjroutput_word(size_t indent0, size_t indent1, const wchar_t *word, size_t length, size_t spaces) { 531133008Stjr size_t new_x; 53277807Sru size_t indent = output_in_paragraph ? indent1 : indent0; 533133008Stjr size_t width; 534133008Stjr const wchar_t *p; 535133008Stjr int cwidth; 5361590Srgrimes 537133008Stjr for (p = word, width = 0; p < &word[length]; p++) 538133008Stjr width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1; 539133008Stjr 540133008Stjr new_x = x + pending_spaces + width; 541133008Stjr 54277807Sru /* If either |spaces==0| (at end of line) or |coalesce_spaces_P| 54377807Sru * (squashing internal whitespace), then add just one space; 54477807Sru * except that if the last character was a sentence-ender we 54577807Sru * actually add two spaces. 54677807Sru */ 54777807Sru if (coalesce_spaces_P || spaces==0) 548133008Stjr spaces = wcschr(sentence_enders, word[length-1]) ? 2 : 1; 5498874Srgrimes 55077807Sru if (new_x<=goal_length) { 55177807Sru /* After adding the word we still aren't at the goal length, 55277807Sru * so clearly we add it to the buffer rather than outputing it. 55377807Sru */ 554133008Stjr wmemset(output_buffer+output_buffer_length, L' ', pending_spaces); 55577807Sru x0 += pending_spaces; x += pending_spaces; 556133008Stjr output_buffer_length += pending_spaces; 557133008Stjr wmemcpy(output_buffer+output_buffer_length, word, length); 558133008Stjr x0 += width; x += width; output_buffer_length += length; 55977807Sru pending_spaces = spaces; 56077807Sru } 56177807Sru else { 56277807Sru /* Adding the word takes us past the goal. Print the line-so-far, 56377807Sru * and the word too iff either (1) the lsf is empty or (2) that 56477807Sru * makes us nearer the goal but doesn't take us over the limit, 56577807Sru * or (3) the word on its own takes us over the limit. 56677807Sru * In case (3) we put a newline in between. 56777807Sru */ 56877807Sru if (indent>0) output_indent(indent); 569133008Stjr wprintf(L"%.*ls", (int)output_buffer_length, output_buffer); 57077807Sru if (x0==0 || (new_x <= max_length && new_x-goal_length <= goal_length-x)) { 571133008Stjr wprintf(L"%*ls", (int)pending_spaces, L""); 57277807Sru goto write_out_word; 57377807Sru } 57477807Sru else { 57577807Sru /* If the word takes us over the limit on its own, just 57677807Sru * spit it out and don't bother buffering it. 57777807Sru */ 578133008Stjr if (indent+width > max_length) { 579133008Stjr putwchar('\n'); 58077807Sru if (indent>0) output_indent(indent); 58177807Sruwrite_out_word: 582133008Stjr wprintf(L"%.*ls", (int)length, word); 58377807Sru x0 = 0; x = indent1; pending_spaces = 0; 584133008Stjr output_buffer_length = 0; 58577807Sru } 58677807Sru else { 587133008Stjr wmemcpy(output_buffer, word, length); 588133008Stjr x0 = width; x = width+indent1; pending_spaces = spaces; 589133008Stjr output_buffer_length = length; 59077807Sru } 59177807Sru } 592133008Stjr putwchar('\n'); 59377807Sru output_in_paragraph = 1; 59477807Sru } 5951590Srgrimes} 5961590Srgrimes 59777807Sru/* Process a stream, but just center its lines rather than trying to 59877807Sru * format them neatly. 5991590Srgrimes */ 60077807Srustatic void 60177807Srucenter_stream(FILE *stream, const char *name) { 602133008Stjr wchar_t *line, *p; 60377807Sru size_t length; 604133008Stjr size_t width; 605133008Stjr int cwidth; 60677807Sru while ((line=get_line(stream, &length)) != 0) { 60777807Sru size_t l=length; 608133008Stjr while (l>0 && iswspace(*line)) { ++line; --l; } 60977807Sru length=l; 610133008Stjr for (p = line, width = 0; p < &line[length]; p++) 611133008Stjr width += (cwidth = wcwidth(*p)) > 0 ? cwidth : 1; 612133008Stjr l = width; 613133008Stjr while (l<goal_length) { putwchar(' '); l+=2; } 614133008Stjr wprintf(L"%.*ls\n", (int)length, line); 61577807Sru } 616132178Stjr if (ferror(stream)) { warn("%s", name); ++n_errors; } 6171590Srgrimes} 6181590Srgrimes 61977807Sru/* Get a single line from a stream. Expand tabs, strip control 62077807Sru * characters and trailing whitespace, and handle backspaces. 62177807Sru * Return the address of the buffer containing the line, and 62277807Sru * put the length of the line in |lengthp|. 62377807Sru * This can cope with arbitrarily long lines, and with lines 62477807Sru * without terminating \n. 62577807Sru * If there are no characters left or an error happens, we 62677807Sru * return 0. 62777807Sru * Don't confuse |spaces_pending| here with the global 62877807Sru * |pending_spaces|. 6291590Srgrimes */ 630133008Stjrstatic wchar_t * 63177807Sruget_line(FILE *stream, size_t *lengthp) { 632133008Stjr static wchar_t *buf=NULL; 63377807Sru static size_t length=0; 63477807Sru size_t len=0; 635133008Stjr wint_t ch; 63677807Sru size_t spaces_pending=0; 63789268Sru int troff=0; 638133008Stjr size_t col=0; 639133008Stjr int cwidth; 6401590Srgrimes 641133008Stjr if (buf==NULL) { length=100; buf=XMALLOC(length * sizeof(wchar_t)); } 642133008Stjr while ((ch=getwc(stream)) != '\n' && ch != WEOF) { 64389268Sru if (len+spaces_pending==0 && ch=='.' && !format_troff) troff=1; 64477807Sru if (ch==' ') ++spaces_pending; 645133008Stjr else if (troff || iswprint(ch)) { 64677807Sru while (len+spaces_pending >= length) { 647133008Stjr length*=2; buf=xrealloc(buf, length * sizeof(wchar_t)); 64877807Sru } 649133008Stjr while (spaces_pending > 0) { --spaces_pending; buf[len++]=' '; col++; } 65077807Sru buf[len++] = ch; 651133008Stjr col += (cwidth = wcwidth(ch)) > 0 ? cwidth : 1; 65277807Sru } 65377807Sru else if (ch=='\t') 654133008Stjr spaces_pending += tab_width - (col+spaces_pending)%tab_width; 655133008Stjr else if (ch=='\b') { if (len) --len; if (col) --col; } 65677807Sru } 65777807Sru *lengthp=len; 658133008Stjr return (len>0 || ch!=WEOF) ? buf : 0; 6591590Srgrimes} 6601590Srgrimes 66177807Sru/* (Re)allocate some memory, exiting with an error if we can't. 6621590Srgrimes */ 66377807Srustatic void * 66477807Sruxrealloc(void *ptr, size_t nbytes) { 66577807Sru void *p = realloc(ptr, nbytes); 66677807Sru if (p == NULL) errx(EX_OSERR, "out of memory"); 66777807Sru return p; 6681590Srgrimes} 669