Postscript IDE
Volume Number: 17 (2001)
Issue Number: 4
Column Tag: Programming Techniques
A Postscript IDE via a BBEdit Plug-In
By Larry Taylor
Using BBEdit + Distiller + Acrobat to create postscript files with a minimum of fuss
Introduction
Seven or eight years back, MacTech devoted an issue to the postscript page description language and neat things that you could do with it (Vol. 9, 1993, Issue 4). This briefly inspired me to try some things I'd wanted to do, but the lack of any sort of programming environment was a real hindrance - sending your code to a printer and waiting to see what happens is slow, frustrating and a big waste of paper. When Adobe came out with Distiller, life improved some. You could write your code using a text editor (such as BBEdit), open the file in Distiller and then read the resulting pdf file using Reader. All in all, not too bad. This got me doing postscript programming again, but it wasn't a true Mac experience. Ideally, I wanted to be able to type some code, execute some key combination that compiles the code, and then execute another key combination and have the results displayed.
In volume 14, 1998, Issue 6, MacTech had an article on BBEdit plug-ins by Steve Sheets. I read the article with some interest, but as all of his examples dealt with manipulating text in BBEdit windows, nothing clicked and I passed on, Then one day it occurred to me that there must be commands for file manipulation as well. After all, there is the old chestnut "Send Postscript" that I had first used to send my postscript files to the printer. It ought to be possible to write a plug-in to mimic "Send Postscript" but using Distiller and Acrobat instead of a printer: specifically, a plug-in with the following behavior.
Take the text in the front window and find the associated file. Use some rule to associate a pdf file to BBEdit file and find it. If the modification date on the pdf file is older than that on the BBEdit file, send the BBEdit file to Distiller; otherwise send the pdf file to Reader or Acrobat.
The rest of this article describes such a plug-in and how you can code it and get it working. I will try to duplicate as little of Steve Sheets' article as possible, subject to this article's being self-contained, so for a detailed discussion of how BBEdit plug-ins work, go read Sheets' article.
Caveats and Quibbles
I have used this plug-in for several months but it is not a commercial quality postscript development environment. It works quite well for small projects and I recommend it for doing eps files. If you would like a postscript file to start on, http://www.nd.edu/~taylor/ComputerStuff/Postscript/graphpaper.html will get you a simple postscript program for graphing functions together with some additional examples.
Here are a some minor annoyances and their work-arounds.
- You have to invoke the plug-in twice to get from changes in your postscript code to the displayed pdf file. Live with it.
- If you leave the pdf file open in Acrobat and try to distill the BBEdit file again, Distiller puts up an error message that it can't delete the pdf file and halts. Just close the pdf file and try again.
- When you invoke the plug-in the application being called comes to the foreground. You need to get back to BBEdit to run the plug-in again. Since the Distiller window is small, a simple mouse click will do the trick. Since any error messages you may generate appear in the Distiller window, it is actually a feature to have it foremost. The Acrobat window is usually large and getting back to the BBEdit window may involve more than just a mouse click, but this is also a feature since it encourages you to close the Acrobat window before doing more work on your code, thus avoiding annoyance 2".
First Steps
If you have never programmed in C before, this may not be a good initial project, but if you are reasonably familiar with your C compiler you should be able to complete this project. I use CodeWarrior as my C compiler so my remarks will apply precisely to their setup but only minor modifications should be needed for other environments.
You need the BBEdit Extension SDK. This can be obtained from the BareBones website via http://www.barebones.com/support/developer/pluginsdk.html and follow the link. When un-stuffed, you will have a folder, BBEdit Extension SDK, with three folders and two files. The file Writing BBEdit Extensions.srd is a stand alone document describing the subroutines available to you, their argument structure and what is returned. It also has specific suggestions to help you get your CodeWarrior or Symantec environment working.
My suggestion is to go immediately to the examples, find HelloWorld and compile it. In my case, CodeWarrior wanted to update to a newer version which came off without a hitch, and then a few paths had to be reset. After these annoyances, the project compiled and when the plug-in was added to the BBEdit Support:Plug-Ins folder, the project worked as advertised. HelloWorld is an excellent project to start with since once you get it working, the alterations necessary for this project are mostly a matter of making a few changes and adding code.
The Actual Code
The code below was produced as follows. First I made a copy of the working HelloWorld project and renamed all the files PostscriptIDE.whatever. Then I opened the PostscriptIDE.rsrc file and added an alert with one button to dismiss the alert and one static text box with an entry of ^0. The resource ID of the alert was 128. Then the project file PostscriptIDE.µ was opened. Once in CodeWarrior I opened the PostscriptIDE Settings dialog, selected 68K Target and changed the Resource Name to PostscriptIDE. The name here" becomes the name the plug-in has in the Tools menu in BBEdit. The files in the project still had their HelloWorld names so I deleted HelloWorld.c and HelloWorld.rsrc and replaced them with their PostscriptIDE counterparts.
Next I opened the PostscriptIDE.c file and deleted all the code between the EnterCodeResource() and the ExitCodeResource(). The Enter/Exit routines must blanket our code in order to correctly interface with BBEdit, so I left them. One also needs to be careful, especially with error handling, not to return control to BBEdit without going through ExitCodeResource(). Finally, I added code to produce the program you see below.
The code in main is straightforward. A pointer to the front window is one of the variables we are handed when our code starts up and we check first that it is not NULL and if it is not, then we make sure we have a window of kind userKind since all the subsequent calls to the BBEdit subroutines that we use warn that they should only be called on windows of kind userKind. If either of these tests fail, we put up our alert and when the user dismisses it, we return control to BBEdit via the ExitCodeResource() routine.
The call to the subroutine bbxtGetWindowContents() returns a handle to the contents of the front window. Assuming this works, we check that the file starts with !%PS, since any legitimate Postscript file must start this way. If this fails, we put up our alert and again exit gracefully. If our check is successful, then we get the file information associated to the front window. Assuming we get a valid file, we turn our information into an FSSpec for the file and call the subroutine Ship_to_APPL which does most of the work. If we fail here there are two possibilities. There may be no file to get, if for example we have not yet saved it. In this case we put up an alert. We also might fail to create the FSSpec from the data BBEdit returns. We consider this unlikely but put up the BBEdit alert box for handling this."
Next come the declarations for two subroutines. The subroutine FSpGetHPBRec takes an FSSpec pointer and fills in an HParamBlockRec for the file which lets us get at the modification date. The subroutine Calculate_pdf_file takes an FSSpec pointer to the BBEdit file and returns an FSSpec pointer to the pdf file.
The Ship_to_APPL subroutine does the real work. First we calculate the name of the pdf file from that of the BBEdit file by calling our subroutine. Then we try to get the HParamBlockRec for the pdf file. If this fails, we prepare to ship the BBEdit file to Distiller by setting Res to 'DSTL', the signature for Distiller, and file to point to the BBEdit file. If we get an HParmBlockRec for the pdf file, then we also get one for the BBEdit file and compare the modification dates. (If we fail to get the modification date for the BBEdit file we put up the standard BBEdit alert.) Depending on how the modification dates compare, we set Res to 'DSTL' and file to point to the BBEdit file or else we set Res to "CARO' and file to point to the pdf file. (An annoyance arises here - 'CARO' is the signature for both Acrobat and Reader so which of these will be used to open the pdf file depends on your setup. Find any pdf file and double click it. Whichever application opens this file will be used by this plug-in.) Finally, we call bbxtSendOpenDoc() which opens the file pointed to by file in the application with signature Res. Again, this routine can return an error and we just pass it to the BBEdit alert.
The code for the two subroutines is straightforward.
- FSpGetHPBRec() just sets some entries in the HParamBlockRec and then calls PBHGetFInfo() which fills in the HParamBlockRec for us. Whatever error code we get, we return.
- Calculate_pdf_file takes the FSSpec for the BBEdit file and produces an FSSpec for the .pdf file by stripping off a .ps, .eps or .epsf ending if there is one and appending .pdf. We do check that the file name will not be too long and truncate if necessary. The volume and parent directory for the .pdf file are the same as for the BBEdit file.
- The code.
The first part is in small type so that it formats identically to the first part of the file HelloWorld.c. The regular font size denotes code that has been changed from this file after the deletions discussed above.
#include <ExternalInterface.h>
// deal with A4
#ifdef THINK_C
#include <SetupA4.h>
#define EnterCodeResource() do { RememberA0(); SetUpA4(); } while (0)
#define ExitCodeResource() do { RestoreA4(); } while (0)
#endif
#ifdef __MWERKS__
#include <A4Stuff.h>
#endif
#define ALERTID 128
void Ship_to_APPL( ExternalCallbackBlock *callbacks,
FSSpec* file);
pascal void main( ExternalCallbackBlock *callbacks,
WindowPtr w)
{
Str63 m1="\pThe front BBEdit window does not start with";
Str63 m2="\p %!PS on the first line.";
Str15 m3="\pNo file found - ";
Str63 m4="\pprobably need to save first!";
Str255 fName;
short vRef;
long dirID;
FSSpec file;
OSErr err;
Handle window_text;
EnterCodeResource();
if (w!=0 && ((WindowPeek)w)->windowKind==userKind) {
window_text=bbxtGetWindowContents(callbacks,w);
if( window_text!=0 && *((long*)*window_text)=='%!PS' ) {
/*Force window text to start with %!PS */
bbxtGetDocInfo(callbacks,w,fName,&vRef,&dirID);
if(fName[0]!=0) {
err=FSMakeFSSpec(vRef,dirID,fName,&file);
if(err==noErr) {
Ship_to_APPL(callbacks,&file);
}
else {
bbxtReportOSError(callbacks,err);
}
}
else{
ParamText(m3,m4,"\p","\p");
Alert(ALERTID,bbxtGetStandardFilter(callbacks));
}
}
else {
ParamText(m1,m2,"\p","\p");
Alert(ALERTID,bbxtGetStandardFilter(callbacks));
}
}
else {
ParamText(m1,m2,"\p","\p");
Alert(ALERTID,bbxtGetStandardFilter(callbacks));
}
ExitCodeResource();
}
OSErr FSpGetHPBRec(HParmBlkPtr,FSSpec*);
void Calculate_pdf_file(FSSpec *pdf_file, FSSpec *ps_file);
void Ship_to_APPL( ExternalCallbackBlock *callbacks,
FSSpec* ps_file)
{ FSSpec pdf_file, *file;
HParamBlockRec ps, pdf;
OSErr err;
OSType Res;
Calculate_pdf_file(&pdf_file,ps_file);
err=FSpGetHPBRec(&pdf,&pdf_file);
if(err!=noErr) { /* If no pdf_file ship to Distiller.*/
Res='DSTL';file=ps_file;
}
else{
err=FSpGetHPBRec(&ps,ps_file);
if(err==noErr) {
/* If there is such a file,
get modification dates for ps_file and pdf_file.*/
/* If date for pdf_file is later, send pdf_file to Reader,
otherwise send ps_file to Distiller */
if( (unsigned long)pdf.fileParam.ioFlMdDat
<=
(unsigned long)ps.fileParam.ioFlMdDat ) {
Res='DSTL';file=ps_file;
}
else {
Res='CARO';file=&pdf_file;
}
}
else {
/*This should not happen!*/
bbxtReportOSError(callbacks,err);
return;
}
}
err=bbxtSendOpenDoc(callbacks,Res,0,file,true);
if(err!=noErr) {bbxtReportOSError(callbacks,err);}
}
OSErr FSpGetHPBRec(HParmBlkPtr hpbp, FSSpec* file){
hpbp->fileParam.ioVRefNum=file->vRefNum;
hpbp->fileParam.ioFDirIndex=0;
hpbp->fileParam.ioNamePtr=file->name;
hpbp->fileParam.ioDirID=file->parID;
return(PBHGetFInfo(hpbp,false));
}
void Calculate_pdf_file(FSSpec *pdf_file, FSSpec *ps_file) {
short rr;
Str15 offset;
*pdf_file=*ps_file;
rr=offset[0]=pdf_file->name[0];
offset[1]=offset[0]-1;offset[2]=offset[0]-2;
offset[3]=offset[0]-3;offset[4]=offset[0]-4;
if( pdf_file->name[offset[2]]=='.' &&
pdf_file->name[offset[1]]=='p' &&
pdf_file->name[offset[0]]=='s' ) {
rr=pdf_file->name[0]-3;
}
else if(
pdf_file->name[offset[4]]=='.' &&
pdf_file->name[offset[3]]=='e' &&
pdf_file->name[offset[2]]=='p' &&
pdf_file->name[offset[1]]=='s' &&
pdf_file->name[offset[0]]=='f' ) {
rr=pdf_file->name[0]-5;
}
else if(
pdf_file->name[offset[3]]=='.' &&
pdf_file->name[offset[2]]=='e' &&
pdf_file->name[offset[1]]=='p' &&
pdf_file->name[offset[0]]=='s' ) {
rr=pdf_file->name[0]-4;
}
if(rr>27) {rr=27;}
pdf_file->name[0]=rr;
pdf_file->name[++pdf_file->name[0]]='.';
pdf_file->name[++pdf_file->name[0]]='p';
pdf_file->name[++pdf_file->name[0]]='d';
pdf_file->name[++pdf_file->name[0]]='f';
}
Conclusion
After compiling the project, drop the file into the BBEdit Support:Plug-Ins folder and restart BBEdit. I like to add a key stroke combination to run the plug-in. To do this, select Tools List from the Tools menu, select your new plug-in, click on the Set Key button and type the desired key stroke combination.
This plug-in turns BBEdit & Distiller & Reader into a workable postscript development environment. Several things are missing from an ideal environment, mostly in the debugging line. Under the current scheme, it is Distiller that would have to supply the debugging capabilities and at the moment such capabilities are minimal. This article is not the place to discuss postscript programming, but the green book, Postscript Language Program Design (ISBN 0-201-14396-8, 1988, Addison-Wesley), has a very useful section on debugging. In particular, its message routine
/msg{
print(\n)print flush
} bind def
can be used to print messages to the Distiller window such as
(Yea! We got here.) msg
which can be used to locate the source of difficulties - not ideal but workable, as many of us old guys can attest from much debugging in many different languages.
The author is a research mathematician and professor who spends too much time fooling around with this sort of thing. More stuff at <http://www.nd.edu/~taylor>.