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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
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 »

Price Scanner via MacPrices.net

13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more
Sunday Sale: Apple iPad Magic Keyboards for 1...
Walmart has Apple Magic Keyboards for 12.9″ iPad Pros, in Black, on sale for $150 off MSRP on their online store. Sale price for online orders only, in-store price may vary. Order online and choose... Read more

Jobs Board

Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.