/* br.c by RJB CSUSB 1987 Program to word wrap text. #define, backtrack,... Purpose: This program word wraps text. br wout out reads 'stdin' as text and writes out the same text word wrapped to width wout. Note: Example of the Jackson JSP/JSD style */ /*#define DEBUG*/ #include #ifdef DEBUG #define db(f,x) fprintf(stderr," "#x" =<"#f">\n",x); #define dbs(x) fprintf(stderr,"%s\n",x); #else #define db(f,x) ; #define dbs(s) ; #endif #define SP ' ' #define HT '\t' #define HTWIDTH 8 #define CR '\n' #define DEL (int)0377 #define BUFSIZE 250 #define MAXWD BUFSIZE #define MINWOUT 10 int wout=75; /* width of desired output in characters*/ /*K & R p79 backtrackable input package:getch and ungetch*/ /*Misfeature - getchar after EOF stopped, RJB May 87 */ int buf[BUFSIZE]; int bp=0;/*next free in buf*/ int getch() { static int lastgetchar=0; dbs("getch") return( (bp > 0) ? buf [ --bp ] :(lastgetchar!=EOF)? (lastgetchar=getchar()) :lastgetchar ); } ungetch(c) int c; { dbs("ungetch") if(bp>BUFSIZE){fprintf(stderr,"br: word too long to handle\n");exit(1);} else buf[bp++]=c; } main(argc,argv) int argc; char *argv[]; { int ch,n; int wd[MAXWD], ws[MAXWD]; /* WARNING - these are not null terminated strings. wdp (resp. wsp) point to the next empty place in wd (resp. ws) Only wd[0..wdp-1] are actual characters (resp. ws[0...wsp-1]) */ int *wdp, *wsp, *p; if(argc>2){fprintf(stderr,"usage: br width_out\n");exit(1);} else if(argc==2) wout=abs(atoi(argv[1])); else /*assume default width*/ if(wout>MAXWD) {fprintf(stderr,"br: %d too large > %d for this version\n",wout,MAXWD); exit(1); } if(woutwd){ ungetch(ch); while(wdp>wd)ungetch(*--wdp); ch=getch(); } while(1){n=0;dbs("posit break") while(1){dbs("posit fits") if(ch>SP && chSP && ch!=DEL){dbs("wdch") db(%o,ch) if(n==wout) goto didnotfit; n++; *wdp++ = ch;/*wdp-wd<=n<=woutwout-1)goto didnotfit; for(p=ws;pwd){ ungetch(ch); while(wdp>wd)ungetch(*--wdp); ch=getch(); } putc(CR,stdout); end_of_line:dbs("end of line") } nobreaks:/*CP_ok_line*/ dbs("end of input line") putc(CR,stdout); ch=getch(); } exit(0); }