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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but 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 MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
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
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and 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.