TweetFollow Us on Twitter

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.

  1. You have to invoke the plug-in twice to get from changes in your postscript code to the displayed pdf file. Live with it.
  2. 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.
  3. 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>.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Jump into one of Volkswagen's most...
We spoke about PUBG Mobile yesterday and their Esports development, so it is a little early to revisit them, but we have to because this is just too amusing. Someone needs to tell Krafton that PUBG Mobile is a massive title because out of all the... | Read more »
PUBG Mobile will be releasing more ways...
The emergence of Esports is perhaps one of the best things to happen in gaming. It shows our little hobby can be a serious thing, gets more people intrigued, and allows players to use their skills to earn money. And on that last point, PUBG Mobile... | Read more »
Genshin Impact 5.1 launches October 9th...
If you played version 5.0 of Genshin Impact, you would probably be a bit bummed by the lack of a Pyro version of the Traveller. Well, annoyingly HoYo has stopped short of officially announcing them in 5.1 outside a possible sighting in livestream... | Read more »
A Phoenix from the Ashes – The TouchArca...
Hello! We are still in a transitional phase of moving the podcast entirely to our Patreon, but in the meantime the only way we can get the show’s feed pushed out to where it needs to go is to post it to the website. However, the wheels are in motion... | Read more »
Race with the power of the gods as KartR...
I have mentioned it before, somewhere in the aether, but I love mythology. Primarily Norse, but I will take whatever you have. Recently KartRider Rush+ took on the Arthurian legends, a great piece of British mythology, and now they have moved on... | Read more »
Tackle some terrifying bosses in a new g...
Blue Archive has recently released its latest update, packed with quite an arsenal of content. Named Rowdy and Cheery, you will take part in an all-new game mode, recruit two new students, and follow the team's adventures in Hyakkiyako. [Read... | Read more »
Embrace a peaceful life in Middle-Earth...
The Lord of the Rings series shows us what happens to enterprising Hobbits such as Frodo, Bilbo, Sam, Merry and Pippin if they don’t stay in their lane and decide to leave the Shire. It looks bloody dangerous, which is why September 23rd is an... | Read more »
Athena Crisis launches on all platforms...
Athena Crisis is a game I have been following during its development, and not just because of its brilliant marketing genius of letting you play a level on the webpage. Well for me, and I assume many of you, the wait is over as Athena Crisis has... | Read more »
Victrix Pro BFG Tekken 8 Rage Art Editio...
For our last full controller review on TouchArcade, I’ve been using the Victrix Pro BFG Tekken 8 Rage Art Edition for PC and PlayStation across my Steam Deck, PS5, and PS4 Pro for over a month now. | Read more »
Matchday Champions celebrates early acce...
Since colossally shooting themselves in the foot with a bazooka and fumbling their deal with EA Sports, FIFA is no doubt scrambling for other games to plaster its name on to cover the financial blackhole they made themselves. Enter Matchday, with... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra available today at Apple fo...
Apple has several Certified Refurbished Apple Watch Ultra models available in their online store for $589, or $210 off original MSRP. Each Watch includes Apple’s standard one-year warranty, a new... Read more
Amazon is offering coupons worth up to $109 o...
Amazon is offering clippable coupons worth up to $109 off MSRP on certain Silver and Blue M3-powered 24″ iMacs, each including free shipping. With the coupons, these iMacs are $150-$200 off Apple’s... Read more
Amazon is offering coupons to take up to $50...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for up to $110 off MSRP, each including free delivery. Prices are valid after free coupons available on each mini’s product page, detailed... Read more
Use your Education discount to take up to $10...
Need a new Apple iPad? If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $100 off the... Read more
Apple has 15-inch M2 MacBook Airs available f...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
Mac Studio with M2 Max CPU on sale for $1749,...
B&H Photo has the standard-configuration Mac Studio model with Apple’s M2 Max CPU in stock today and on sale for $250 off MSRP, now $1749 (12-Core CPU and 32GB RAM/512GB SSD). B&H offers... Read more
Save up to $260 on a 15-inch M3 MacBook Pro w...
Apple has Certified Refurbished 15″ M3 MacBook Airs in stock today starting at only $1099 and ranging up to $260 off MSRP. These are the cheapest M3-powered 15″ MacBook Airs for sale today at Apple.... Read more
Apple has 16-inch M3 Pro MacBook Pro in stock...
Apple has a full line of 16″ M3 Pro MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $440 off MSRP. Each model features a new outer case, shipping is free, and an... Read more
Apple M2 Mac minis on sale for $120-$200 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $110-$200 off MSRP this weekend, each including free delivery: – Mac mini M2/256GB SSD: $469, save $130 – Mac mini M2/512GB SSD: $689.... Read more
Clearance 9th-generation iPads are in stock t...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on clearance sale for starting at only $199 on their online store for a limited time. Sale prices for online orders only, in-store prices may vary... Read more

Jobs Board

Senior Mobile Engineer-Android/ *Apple* - Ge...
…Trust/Other Required:** NACI (T1) **Job Family:** Systems Engineering **Skills:** Apple Devices,Device Management,Mobile Device Management (MDM) **Experience:** 10 + Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Full Time (80 hrs/pay period) Evenings General Summary Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.