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

Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.