Writing scripts to change fonts in FontForge

FontForge includes two interpreters so you can write scripts to modify fonts. One of these interpreters is python, one is a legacy language I came up with. FontForge may be configured with either or both of these. If configured with both then fontforge will make a guess at which to use based on the script file's extension ("py" means use the python interpreter, "ff" or "pe" means use the old interpreter)

Invoking scripts

If you start fontforge with a script on the command line it will not put up any windows and it will exit when the script is done. The script can be in a file, or just a string presented as an argument. You may need to specify which interpreter to use with the -lang argument.

$ fontforge -script scriptfile.pe {arguments}
$ fontforge -c "script-string" {arguments}
$ fontforge -lang={ff|py} -c "script-string"

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

If you wish FontForge to read a script from stdin then you can use "-" as a "filename" for stdin. (If you build FontForge without X11 then fontforge will attempt to read a script file from stdin if none is given on the command line.)

You can also start a script from within FontForge 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 glyph out of splines, instead it allows you to do high level modifications to glyphs.

If you set the environment variable FONTFORGE_VERBOSE (it doesn't need a value, just needs to be set) then FontForge will print scripts to stdout as it executes them.

You may set the environment variable FONTFORGE_LANGUAGE to either "py" (for python) or "ff" or "pe" (for native scripting) as another way to determne what interpreter to use.

Python scripting

Is described elsewhere.

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 FontForge's internal procedures it will be executed, otherwise it will be assumed to be a filename containing another fontforge 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. At most 25 arguments can be passed to a procedure.

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.
The foreach statement requires that there be a current font. It executes the statements once for each glyph in the selection. Within the statements only one glyph at a time will be selected. After execution the selection will be restored to what it was initially. (Caveat: Don't reencode the font within a foreach statement).
Statements are terminated either by a new line (you can break up long lines with backslash newline) 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

FontForge 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. FontForge 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, FontForge 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. Often the description here is sketchy, look at the menu item for more information.

Built-in procedures in alphabetic order

- A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z -

Built-in procedures that do not require a loaded font

Built-in procedures that act like the File Menu

File Manipulation

Built-in procedures that act like the Edit Menu

Built-in procedures that act like the Select Menu

Built-in procedures that act like the Element Menu

Font Info

Glyph Info

Built-in procedures that handle Advanced Typography

Built-in procedures that act like the Encoding Menu

Built-in procedures that act like the Hint Menu

Built-in procedures that act like the Metrics Menu

Multiple master routines

CID routines

User Interaction

Preferences

Math

Unicode

String manipulation

Character Manipulation

Arrays

Miscellaneous

Deprecated Names


Examples

Example 1:

#Set the color of all selected glyphs to be yellow
#designed to be run within an interactive fontforge session.
foreach
  SetCharColor(0xffff00)
endloop

Example 2:

#!/usr/local/bin/fontforge
#This is the sfddiff script which compares two fonts

if ( Strtol($version) < 20060330 )
  Error( "Please upgrade to a more recent version of fontforge" )
endif

flags=0x789
outfile=""

while ( $argc > 1 && Strsub($1,0,1)=="-" )
  temp = $1
  if ( Strsub(temp,1,2)=='-' )
    temp = Strsub(temp,1)
  endif

  if ( temp=="-ignorehints" )
    flags = flags & ~0x8
  elseif ( temp=="-ignorenames" )
    flags = flags & ~0x100
  elseif ( temp=="-ignoregpos" )
    flags = flags & ~0x200
  elseif ( temp=="-ignoregsub" )
    flags = flags & ~0x400
  elseif ( temp=="-ignorebitmaps" )
    flags = flags & ~0x80
  elseif ( temp=="-exact" )
    flags = flags | 0x2
  elseif ( temp=="-warn" )
    flags = flags | 0x44
  elseif ( temp=="-merge" )
    flags = flags | 0x1800
    shift
    outfile = $1
  elseif ( temp=="-help" )
    Print( "sfddiff: [--version] [--help] [--usage] [--ignorehints] [--ignorenames] [--ignoregpos] [--ignoregsup] [--ignorebitmaps] [--warn] [--exact] fontfile1 fontfile2" )
    Print( " Compares two fontfiles" )
    Print( " --ignorehints: Do not compare postscript hints or truetype instructions" )
    Print( " --ignorenames: Do not compare font names" )
    Print( " --ignoregpos:  Do not compare kerning, etc." )
    Print( " --ignoregsub:  Do not compare ligatures, etc." )
    Print( " --ignorebitmaps: Do not compare bitmap strikes" )
    Print( " --exact:       Normally sfddiff will match contours which are not exact" )
    Print( "                but where the differences are slight (so you could compare" )
    Print( "                truetype and postscript and get reasonable answers). Also" )
    Print( "                normally sfddiff will unlink references before it compares" )
    Print( "                (so you can compare a postscript font (with no references)" )
    Print( "                to the original source (which does have references)). Setting")
    Print( "                this flag means glyphs must match exactly.")
    Print( " --warn:        Provides a warning when an exact match is not found" )
    Print( " --merge outfile: Put any outline differences in the backgrounds of" )
    Print( "                appropriate glyphs" )
return(0)
  elseif ( temp=="-version" )
    Print( "Version 1.0" )
return(0)
  else
break
  endif
  shift
endloop

if ( $argc!=3 || $1=="--usage" || $1=="-usage" )
  Print( "sfddiff: [--version] [--help] [--usage] [--ignorehints] [--ignorenames] [--ignoregpos] [--ignoregsup] [--ignorebitmaps] [--warn] [--exact] [--merge outfile] fontfile1 fontfile2" )
return(0)
endif

Open($2)
Open($1)
CompareFonts($2,"-",flags)
if ( outfile!="" )
  Save(outfile)
endif

Example 3:

#!/usr/local/bin/fontforge
#Take a Latin font and apply some simple transformations to it
#prior to adding cyrillic letters.
#can be run in a non-interactive fontforge session.
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 FontForge 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 script 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 (in python this is fontforge.activeFontInUI()).

Note that if you try to print from a script the output will go to stdout. If you have invoked fontforge from a window manager's menu stdout will often be bound to /dev/null and not useful. Try starting fontforge from the command line instead.

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 --