PostScript is so elegant

Ok, most people don’t code in PostScript. Granted, like SQL, it’s one of those languages that’s usually coded by a program written in another language. But it’s so incredibly elegant!

PostScript is like coding in reverse polish. Put as many parameters as are needed on the stack, then run the function. The answer is on the stack, ready to be the parameter in the next function. Need to move stuff out of the way? ‘exch’-ange arguments.

A google board post led me to the most elegant auto-paging and auto-line-wrap function. The auto-paging is easy: when you’re moving to the next line, if you’ll go off the page, do the show page and new page routines first. The line wrap a bit more complex though. It splits by spaces, compares the length of the first word it got back against the right margin minus the current point, and decides if it needs to line wrap before printing this word. Then it displays the space. The elegant part? Argument 2 of the split function’s return value is “the rest”. Called in a loop, it cycles through all the words on a page, line-breaking as needed.

I posted the gory details here:

% Is the word too long for the space on the line?
/toofar? {dup stringwidth pop currentpoint pop add RM gt} bind def
% Show a word, line wrap if needed
/showword {toofar? {L} if show} def
% Show text, line wrap if needed
% in a loop, break by spaces, and print each word.
% If there isn't a space left, be done.
/S { {( ) search exch showword not {exit} if show} loop} def

(L is the “go to next line” function, RM is the right margin var.)

On Windows, I ran it though Ghostscript on huge documents with no difference. On Unix though, it dogged the Ghostscript engine to death. (My awk script ran like a dream though.)

Rob