Writing scripts to change fonts in PfaEdit

PfaEdit includes an interpreter so you can write scripts to modify fonts.

Starting scripts

If you start pfaedit with a script on the command line it will not put up any windows and it will exit when the script is done.

$ pfaedit -script scriptfile.pe {fontnames}

PfaEdit can also be used as an interpreter that the shell will automatically pass scripts to. If you a mark your script files as executable
    $ chmod +x scriptfile.pe
and begin each one with the line
    #!/usr/local/bin/pfaedit
(or wherever pfaedit happens to reside on your system) then you can invoke the script just by typing
    $ scriptfile.pe {fontnames}

You can also start a script from within PfaEdit with File->Execute Script, and you can use the Preference Dlg to define a set of frequently used scripts which can be invoked directly by menu.

The scripting language provides access to much of the functionality found in the font view's menus. It does not currently (and probably never will) provide access to everything. (If you find a lack let me know, I may put it in for you). It does not provide commands for building up a character out of splines, instead it allows you to do high level modifications to characters.

In general I envision this as being useful for things like taking a latin font and extending it to contain cyrillic characters. So the script might:

Scripting Language

The syntax is rather like a mixture of C and shell commands. Every file corresponds to a procedure. As in a shell script arguments passed to the file are identified as $1, $2, ... $n. $0 is the file name itself. $argc gives the number of arguments. $argv[<expr>] provides array access to the arguments.

Terms can be

There are three different comments supported:

Expressions are similar to those in C, a few operators have been omitted, a few added from shell scripts. Operator precedence has been simplified slightly. So operators (and their precedences) are:

Note there is no comma operator, and no "?:" operator. The precedence of "and" and "or" has been simplified, as has that of the assignment operators.

Procedure calls may be applied either to a name token, or to a string. If the name or string is recognized as one of PfaEdit's internal procedures it will be executed, otherwise it will be assumed to be a filename containing another pfaedit script file, this file will be invoked (since filenames can contain characters not legal in name tokens it is important to allow general strings to specify filenames). If the procedure name does not contain a directory then it is assumed to be in the same directory as the current script file.

Arrays are passed by reference, strings and integers are passed by value.

Variables may be created by assigning a value to them (only with the "="), so:
    i=3
could be used to define "i" as a variable. Variables are limited in scope to the current file, they will not be inherited by called procedures.

A statement may be

As with C, non-zero expressions are defined to be true.
A return statement may be followed by a return value (the expression) or a procedure may return nothing (void).
The shift statement is stolen from shell scripts and shifts all arguments down by one. (argument 0, the name of the script file, remains unchanged.
Statements are terminated either by a new line or a semicolon.

Trivial example:

i=0;	#semicolon is not needed here, but it's ok
while ( i<3 )
   if ( i==1 /* pointless comment */ )
	Print( "Got to one" )	// Another comment
   endif
   ++i
endloop

PfaEdit maintains the concept of a "current font" almost all commands refer only to the current font (and require that there be a font). If you start a script with File->Execute Script, the font you were editing will be current, otherwise there will be no initial current font. The Open(), New() and Close() commands all change the current font. PfaEdit also maintains a list of all fonts that are currently open. This list is in no particular order. The list starts with $firstfont.

Similarly when working with cid keyed fonts, PfaEdit works in the "current sub font", and most commands refer to this font. The CIDChangeSubFont() command can alter that.

All builtin variables begin with "$", you may not create any variables that start with "$" yourself (though you may assign to (some) already existing ones)

The following example will perform an action on all loaded fonts:

file = $firstfont
while ( file != "" )
   Open(file)
   /* Do Stuff */
   file = $nextfont
endloop

The built in procedures are very similar to the menu items with the same names.

Print(arg1,arg2,arg3,...)
This corresponds to no menu item. It will print all of its arguments to stdout. It can execute with no current font.
Error(str)
Prints out str as an error message and aborts the current script
AskUser(question[,default-answer])
Asks the user the question and returns an answer. A default-answer may be specified too.
Array(size)
Allocates an array of the indicated size.
a = Array(10)
i = 0;
while ( i<10 )
   a[i] = i++
endloop
a[3] = "string"
a[4] = Array(10)
a[4][0] = "Nested array";
Strsub(str,start[,end])
Returns a substring of the string argument. The substring beings at position indexed by start and ends at the position indexed by end (if end is omitted the end of the string will be used, the first position is position 0). Thus Strsub("abcdef",2,3) == "c" and Strsub("abcdef",2) == "cdef"
Strlen(str)
Returns the length of the string.
Strstr(haystack,needle)
Returns the index of the first occurance of the string needle within the string haystack (or -1 if not found).
Strrstr(haystack,needle)
Returns the index of the last occurance of the string needle within the string haystack (or -1 if not found).
Strcasestr(haystack,needle)
Returns the index of the first occurance of the string needle within the string haystack ignoring case in the search (or -1 if not found).
Strcasecmp(str1,str2)
Compares the two strings ignoring case, returns zero if the two are equal, a negative number if str1<str2 and a positive number if str1>str2
Strtol(str[,base])
Parses as much of str as possible and returns the integer value it represents. A second argument may be used to specify the base of the conversion (it defaults to 10). Behavior is as for strtol(3).
Strskipint(str[,base])
Parses as much of str as possible and returns the offset to the first character that could not be parsed.
Open(filename)
This makes the font named by filename be the current font. If filename has not yet been loaded into memory it will be loaded now. It can execute with no current font.
New()
This creates a new font. It can execute with no current font.
Close()
This frees up any memory taken up by the current font and drops it off the list of loaded fonts. After this executes there will be no current font.
Save([filename])
If no filename is specified then this saves the current font back into its sfd file (if the font has no sfd file then this is an error). With one argument it executes a SaveAs command, saving the current font to that filename.
Generate(filename[,bitmaptype[,fmflags]])
Generates a font. The type of font is determined by the extension of the filename. If present, bitmaptype may be one of:

If you do not wish to generate an outline font then give the filename the extension of ".bdf".
fmflags controls whether an afm or pfm file should be generated

Import
Either imports a bitmap font into the database, or imports background image[s] into various characters. There may be one or two arguments. The first must be a string representing a filename. The extension of the file determines how the import procedes. If present the second argument must be an integer, if the first argument is a bitmap font then the second argument controls whether it is imported into the bitmap list (0) or to fill up the backgrounds of characters (1).
MergeKern(filename)
Loads Kerning info out of either an afm or a tfm file and merges it into the current font.
Quit(status)
Causes PfaEdit to exit with the given status. It can execute with no current font.
Cut
Makes a copy of all selected characters and saves it in the clipboard, then clears out the selected characters
Copy
Makes a copy of all selected characters.
CopyReference
Makes references to all selected characters and stores them in the clipboard.
CopyWidth
Stores the widths of all selected characters in the clipboard
CopyVWidth
Stores the vertical widths of all selected characters in the clipboard
CopyLBearing
Stores the left side bearing of all selected characters in the clipboard
CopyRBearing
Stores the right side bearing of all selected characters in the clipboard
Paste
Copies the clipboard into the current font (removing what was there before)
PasteInto
Copies the clipboard into the current font (merging with what was there before)
Clear
Clears out all selected characters
ClearBackground
Clears the background of all selected characters
CopyFgToBd
Copies all foreground splines into the background in all selected characters
UnlinkReference
Unlinks all references within all selected characters
SelectAll
Selects all characters
SelectNone
Deselects all characters
Select(arg1, arg2, ...)
This clears out the current selection, then for each pair of arguments it selects all characters between (inclusive) the bounds specified by the pair. If there is a final singleton argument then that single character will be selected. An argument may be specified by:
SelectMore(arg1, arg2, ...)
The same as the previous command except that it does not clear the selection, so it extends the current selection.
Reencode(encoding-name)
Reencodes the current font into the given encoding which may be:
iso8859-1, isolatin1, latin1, iso8859-2, latin2, iso8859-3, latin3, iso8859-4, latin4, iso8859-5, iso8859-6, iso8859-7, iso8859-8, iso8859-9, iso8859-10, iso8859-13, iso8859-14, iso8859-15, latin0, koi8-r, AdobeStandardEncoding, win, mac, wansung, big5, johab, jis208, unicode, iso10646-1, one of the user defined encodings, or something of the form "unicode-plane-%x" to represent the x'th iso10646 plane (where the BMP is plane 0).
SetCharCnt(cnt)
Sets the number of characters in the font.
SetFontNames(fontname[,family[,fullname[,weight[,copyright-notice]]]])
Sets various postscript names associated with a font. If a name is omitted (or is the empty string) it will not be changed.
SetItalicAngle(angle)
Sets the postscript italic angle field appropriately.
SetCharName(name[,set-from-name-flag])
Sets the currently selected character to have the given name. If set-from-name-flag is present and is true then it will also set the unicode value and the ligature string to match the name.
SetUnicodeValue(uni[,set-from-value-flag])
Sets the currently selected character to have the given unicode value. If set-from-value-flag is present and is true then it will also set the name and the ligature string to match the value.
BitmapsAvail(sizes)
Controls what bitmap sizes are stored in the font's database. It is passed an array of sizes. If a size is specified which is not in the font database it will be generated. If a size is not specified which is in the font database it will be removed. A size which is specifed and present in the font database will not be touched.
BitmapsRegen(sizes)
Allows you to update specific bitmaps in an already generated bitmap font. It will regenerate the bitmaps of all selected characters at the specified pixelsizes.
Transform(t1,t2,t3,t4,t5,t6)
Each argument will be divided by 100. and then all selected characters will be transformed by this matrix
HFlip([about-x])
All selected characters will be horizontally flipped about the vertical line through x=about-x. If no argument is given then all selected characters will be flipped about their central point.
VFlip([about-y])
All selected characters will be vertically flipped about the horizontal line through y=about-y. If no argument is given then all selected characters will be flipped about their central point.
Rotate(angle[,ox,oy])
Rotates all selected character the specified number of degrees. If the last two args are specified they provide the origin of the rotation, otherwise the center of the character is used.
Scale(factor[,yfactor][,ox,oy])
All selected characters will be scaled (scale factors are in percent)
Skew(angle[,ox,oy])
All selected characters will be skewed by the given angle.
Move(delta-x,delta-y)
All selected characters will have their points moved the given amount.
ExpandStroke(width)
ExpandStroke(width,caligraphic-angle)
ExpandStroke(width,line cap, line join)
In the first format a line cap of "butt" and line join of "round" are implied.
RemoveOverlap()
Does the obvious.
Simplify()
Does the obvious.
AddExtrema()
RoundToInt()
AutoTrace()
CorrectDirection()
BuildComposit()
BuildAccented()
MergeFonts(other-font-name)

AutoHint()
SetWidth(width)
SetVWidth(vertical-width)
SetLBearing(lbearing)
SetRBearing(rbearing)
SetKern(ch2,offset)
Sets the kern between any selected characters and the character ch2 to be offset. The first argument may be specified as in Select(), the second is an integer representing the kern offset.
RemoveAllKerns()
Removes all kern pairs from the current font.

CIDChangeSubFont(new-sub-font-name)
If the current font is a cid keyed font, this command changes the active sub-font to be the one specified (the string should be the postscript FontName of the subfont)
CIDSetFontNames(fontname[,family[,fullname[,weight[,copyright-notice]]]])
Sets various postscript names associated with the top level cid font. If a name is omitted (or is the empty string) it will not be changed. (this is just like SetFontNames except it works on the top level cid font rather than the current font).
CharCnt()
Returns the number of characters in the current font
InFont(arg)
Returns whether the argument is in the font. The argument may be an integer in which case true is returned if the value is >= 0 and < total number of characters in the font. Otherwise if the argument is a unicode code point or a postscript character name, true is returned if that character is in the font.
WorthOutputting(arg)
Arg is as above. This returns true if the character contains any splines, references or has had its width set.
CharInfo(str)
There must be exactly one character selected in the font, and this returns information on it. The information returned depends on str with the obvious meanings:

Examples:

Select("A")
lbearing = CharInfo("LBearing")
kern = CharInfo("Kern","O")
Select(0u410)
SetLBearing(lbearing)
SetKern(0u41e,kern)


Example:

#!/usr/local/bin/pfaedit
#Take a Latin font and apply some simple transformations to it
#prepriotory to adding cyrillic letters.
Open($1);
Reencode("KOI8-R");
Select(0xa0,0xff);
//Copy those things which look just like latin
BuildComposit();
BuildAccented();

//Handle Ya which looks like a backwards "R"
Select("R");
Copy();
Select("afii10049");
Paste();
HFlip();
CorrectDirection();
Copy();
Select(0u044f);
Paste();
CopyFgToBg();
Clear();

//Gamma looks like an upside-down L
Select("L");
Copy();
Select(0u0413);
Paste();
VFlip();
CorrectDirection();
Copy();
Select(0u0433);
Paste();
CopyFgToBg();
Clear();

//Prepare for editing small caps K, etc.
Select("K");
Copy();
Select(0u043a);
Paste();
CopyFgToBg();
Clear();

Select("H");
Copy();
Select(0u043d);
Paste();
CopyFgToBg();
Clear();

Select("T");
Copy();
Select(0u0442);
Paste();
CopyFgToBg();
Clear();

Select("B");
Copy();
Select(0u0432);
Paste();
CopyFgToBg();
Clear();

Select("M");
Copy();
Select(0u043C);
Paste();
CopyFgToBg();
Clear();

Save($1:r+"-koi8-r.sfd");
Quit(0);

The Execute Script dialog

This dialog allows you to type a script directly in to PfaEdit and then run it. Of course the most common case is that you'll have a script file somewhere that you want to execute, so there's a button [Call] down at the bottom of the dlg. Pressing [Call] will bring up a file picker dlg looking for files with the extension *.pe (you can change that by typing a wildcard sequence and pressing the [Filter] button). After you have selected your scipt the appropriate text to text to invoke it will be placed in the text area.

The current font of the script will be set to whatever font you invoked it from.

The Scripts Menu

You can use the preference dialog to create a list of frequently used scripts. Invoke File->Preferences and select the Scripts tag. In this dialog are ten possible entries, each one should have a name (to be displayed in the menu) and an associated script file to be run.

After you have set up your preferences you can invoke scripts from the font view, either directly from the menu (File->Scripts-><your name>) or by a hot key. The first script you added will be invoked by Cnt-Alt-1, then second by Cnt-Alt-2, and the tenth by Cnt-Alt-0.

The current font of the script will be set to whatever font you invoked it from.

-- Prev -- TOC -- Next --