#!/bin/sh # paginate 0.1.1 (2001-Apr-14-Sat) # Adam M. Costello # paginate [ -L ] [ -n ] [ ... ] # # Concatenates the named files (or stdin if none are specified), # removing all formfeed characters, removing trailing whitespace from # every line, and occasionally replacing contiguous blank lines with a # formfeed so that no page exceeds lines (defaults to 64). # When no blank lines are found soon enough, a formfeed is inserted. # If -n is supplied, a newline follows every formfeed. # # Tries not to end the page with a paragraph in which fewer than two # lines contain letters, unless that paragraph is followed by more than # one blank line. maxpage=64 newline=0 while :; do case "$1" in -L) maxpage=$2 shift 2 ;; -n) newline=1 shift ;; -*) echo "unknown option $1" >&2 exit 1 ;; *) break ;; esac done # paralen is the number of lines in the current paragraph. # gaplen is the number of blanks lines preceeding the current paragraph. # pagelen is the number of lines on the current page: the number of # lines already printed plus gaplen plus paralen. # numlwl is the number of lines with letters seen since the last blank # line. # hardblank is a flag indicating that the current paragraph ends with # a blank line. { cat ${1+"$@"}; echo; echo; } | tr -d '\014' | awk ' BEGIN { paralen = 0; gaplen = 0; pagelen = 0; numlwl = 0; hardblank = 0; } NR == 1 { if (newline) formfeed = "\f\n"; else formfeed = "\f"; } { line = $0; n = match(line, /[ \t]*$/); line = substr(line, 1, n - 1); ++pagelen; if (line != "") { paragraph[++paralen] = line; hardblank = 0; if (match(line, /[a-zA-Z]/)) ++numlwl; if (paralen > maxpage) { prefixlen = maxpage - (pagelen - paralen); if (prefixlen < 0) { printf formfeed; gaplen = 0; pagelen = paralen; prefixlen = maxpage; } for (i = 0; i < gaplen; ++i) print ""; for (i = 1; i <= prefixlen; ++i) print paragraph[i]; printf formfeed; gaplen = 0; for (i = prefixlen + 1; i <= paralen; ++i) paragraph[i - prefixlen] = paragraph[i]; paralen -= prefixlen; pagelen = paralen; } } else { if (paralen == 0) { ++gaplen; } else { if (! hardblank && numlwl < 2) { paragraph[++paralen] = ""; hardblank = 1; } else { if (pagelen - 1 - hardblank > maxpage) { printf formfeed; gaplen = 0; pagelen = paralen + 1; } for (i = 0; i < gaplen; ++i) print ""; for (i = 1; i <= paralen - hardblank; ++i) print paragraph[i]; paralen = 0; gaplen = hardblank + 1; hardblank = 0; } } numlwl = 0; } } ' maxpage=$maxpage newline=$newline