Writing python scripts to change fonts in FontForge

I assume you have a working knowlege of python (because I do not). Python documentation may be found on the web. FontForge implements two python modules -- one great huge one called fontforge which provides access to as much of FontForge's functionality as I've had time to write, and one tiny one called psMat which provides quick access to some useful transformations expressed as PostScript matrices.
psMat
Methods
method args comments
identity () returns an identity matrix as a 6 element tuple
compose (mat1,mat2) returns a matrix which is the composition of the two input transformations
inverse (mat) returns a matrix which is the inverse of the input transformation. (Note: There will not always be an inverse)
rotate (theta) returns a matrix which will rotate by theta. Theta is expressed in radians
scale (x[,y]) returns a matrix which will scale by x in the horizontal direction and y in the vertical. If y is omitted, it will scale by the same amount (x) in both directions
skew (theta) returns a matrix which will skew by theta (to produce a oblique font). Theta is expressed in radians
translate (x,y) returns a matrix which will translate by x in the horizontal direction and y in the vertical
Types
None

fontforge
Methods
method args comments
getPrefs (pref-name) returns the value of the named preference item
setPrefs (pref-name,value) sets the value of the named preference item
savePrefs () Saves the current preference settings
loadPrefs () Loads the user's default preference settings. Not done automatically in a script.
defaultOtherSubrs () Sets the type1 PostScript OtherSubrs to the default value
readOtherSubrsFile (filename) Sets the type1 PostScript OtherSubrs to the stuff found in the file.
loadEncodingFile (filename) Loads an encoding file
loadNamelist (filename) Loads a namelist
loadNamelistDir (dirname) Loads all namelist files in the directory
loadPlugin (filename) Loads a fontforge plugin
loadPluginDir (dirname) Loads all fontforge plugins in the directory
preloadCidmap (filename) Loads a fontforge cidmap file
printSetup (type[,printer|cmd|file,
width,height])
Prepare to print a font sample. The first argument may be one of:
lp
Queues postscript output to the printer using lp. You may use the optional second argument to specify the printer name.
lpr
Queues postscript output to the printer using lpr. You may use the optional second argument to specify the printer name.
ghostview
Displays the output using ghostview (or gv). The second argument is ignored.
command
Use a custom shell command to print the output. The second argument should contain the command and its arguments.
ps-file
Dump the postscript output to a file. The second argument specifies the filename.
pdf-file
Dump the output as pdf to a file. The second argument specifies the filename.

The third and fourth arguments are optional and specify the page size (in points) for the output. The third argument is the page width and the fourth is the height.

These setting remain until changed

unicodeFromName (glyphname) Looks up glyph name in its dictionary and if it is associated with a unicode code point returns that number. Otherwise it returns -1
version () Returns fontforge's version number. This will be a large number like 20070406.
fonts () Returns a tuple of all fonts currently loaded into fontforge for editing
activeFontInUI () If the script were invoked from the File->Execute Script... dialog, this returns the font that was active at the time. Otherwise it returns None.
fontsInFile (filename) Returns a tuple of all fontnames found in the specified file. The tuple may be empty if fontforge couldn't find any.
open (filename) Opens a filename and returns the font it contains. If it does.
parseTTInstrs (string) Returns a binary string each byte of which corresponds to a truetype instruction. The input string should contain a set of instruction names as "SRP0\nMIRP[min,rnd,black]"
unParseTTInstrs (sequence) Reverse of the above. Converts a binary string into a human (sort of) readable string
Types
point
contour
layer
glyphPen
glyph
selection
font

point
Members
member comments
x The x location of the point
y The y location of the point
on_curve Whether this is an on curve point or an off curve point (a control point)
Methods
method args comments
new ([x,y,on-curve]) Creates a new point. Optionally specifying its location
transform (tuple) Transforms the point by the transformation matrix

contour
Members
member comments
is_quadratic Whether the contour should be interpretted as a set of quadratic or cubic splines. Setting this value has the side effect of converting the point list to the appropriate format
closed Whether the contour is open or closed
Sequence Protocol
len(c) The number of points in the contour
c[i] The ith point on the contour. You may assign to this
c[i:j] The contour containing points between i and j. You may assign to this
c + d A contour concatenating c and d. D may be either another contour or a point.
c += d Appends d to c. D may be either another contour or a point.
p in c Returns whether the point p is in the contour c. p may be either a point or a tuple of two numbers
Does not support the repeat concept
Methods
method args comments
new () Creates a new contour
isEmpty () Returns whether the contour is empty (contains no points)
  Contour construction
moveTo (x,y) Adds an initial, on-curve point at (x,y) to the contour
lineTo (x,y[,pos]) Adds an line to the contour. If the optional third argument is give, the line will be added after the pos'th point, otherwise it will be at the end of the contour.
cubicTo ((cp1x,cp1y)(cp2x,cp2y)(x,y)[,pos]) Adds a cubic curve to the contour. If the optional third argument is give, the line will be added after the pos'th point, otherwise it will be at the end of the contour.
quadraticTo ((cpx,cpy)(x,y)[,pos]) Adds a quadratic curve to the contour. If the optional third argument is give, the line will be added after the pos'th point, otherwise it will be at the end of the contour.
insertPoint (point[,pos]) Adds point to the contour. If the optional third argument is give, the line will be added after the pos'th point, otherwise it will be at the end of the contour. The point may be either a point or a tuple with three members (x,y,on_curve)
makeFirst (pos) Rotate the point list so that the pos'th point becomes the first point
isClockwise () Returns whether the contour is drawn in a clockwise direction.
reverseDirection () Reverse the order in which the contour is drawn (turns a clockwise contour into a counter-clockwise one). See also layer.correctDirection.
  Contour manipulation
addExtrema ([flags,emsize]) Extrema should be marked by on-curve points. If a curve lacks a point at an extrema this command will add one. Flags may be one of the following strings
all
Add all missing extrema
only_good
Only add extrema on longer splines (with respect to the em-size)
only_good_rm
As above but also merge away on-curve points which are very close to, but not on, an added extremum
cluster ([within,max]) Moves clustered coordinates to a standard central value. See Also round
merge (pos) Removes the on-curve point a the given position and rearranges the other points to make the curve as similar to the original as possible. (pos may also be a tuple of positions, all of which will be removed) See Also simplify
round ([factor]) Rounds the x and y coordinates. If factor is specified then new-coord = round(factor*old-coord)/factor. See Also cluster
selfIntersects () Returns whether this contour intersects itself.
simplify ([error-bound,flags,tan_bounds,
linefixup,linelenmax])
Tries to remove excess points on the contour if doing so will not perturb the curve by more than error-bound. Flags is a tuple of the following strings
ignoreslopes
Allow slopes to change
ignoreextrema
Allow removal of extrema
smoothcurves
Allow curve smoothing
choosehv
Snap to horizontal or vertical
forcelines
flatten bumps on lines
nearlyhvlines
Make nearly horizontal/vertical lines be so
mergelines
Merge adjacent lines into one
setstarttoextrema
Rotate the point list so that the start point is on an extremum
removesingletonpoints
If the contour contains just one point then remove it

See Also merge

transform (matrix) Transforms the contour by the matrix
random stuff about contours
boundingBox () Returns a tuple representing a rectangle (xmin,ymin, xmax,ymax) into which the contour fits. It is not guaranteed to be the smallest such rectangle, but it will often be.
getSplineAfterPoint (pos) Returns a tuple of two four-element tuples. These tuples are x and y splines for the curve after the specified point.
draw (pen) Draw the contour to the pen argument.

layer
Members
member comments
is_quadratic Whether the contours should be interpretted as a set of quadratic or cubic splines. Setting this value has the side effect of converting the contour list to the appropriate format
Sequence Protocol
len(c) The number of contours in the layer
c[i] The ith contour on the layer. You may assign to this
c + d A layer concatenating c and d. D may be either another layer or a contour.
c += d Appends d to c. D may be either another layer or a contour.
Does not support the repeat, slice and contains concepts
Methods
method args comments
new () Creates a new layer
isEmpty () Returns whether the layer is empty (contains no contour)
addExtrema ([flags,emsize]) Extrema should be marked by on-curve points. If a curve lacks a point at an extrema this command will add one. Flags may be one of the following strings
all
Add all missing extrema
only_good
Only add extrema on longer splines (with respect to the em-size)
only_good_rm
As above but also merge away on-curve points which are very close to, but not on, an added extremum
cluster ([within,max]) Moves clustered coordinates to a standard central value. See also round.
correctDirection () Orients all contours so that external ones are clockwise and internal counter-clockwise. See also contour.isClockwise.
exclude (excluded-layer) Removes the excluded area from the current contours. See also removeOverlap and intersect.
intersect () Leaves only areas in the intersection of contours. See also removeOverlap and exclude.
removeOverlap () Removes overlapping areas. See also intersect and exclude.
round ([factor]) Rounds the x and y coordinates. If factor is specified then new-coord = round(factor*old-coord)/factor. See also cluster.
selfIntersects () Returns whether any of the contours on this layer intersects any other contour (including itself).
simplify ([error-bound,flags,tan_bounds,
linefixup,linelenmax])
Tries to remove excess points on the layer if doing so will not perturb the curve by more than error-bound. Flags is a tuple of the following strings
ignoreslopes
Allow slopes to change
ignoreextrema
Allow removal of extrema
smoothcurves
Allow curve smoothing
choosehv
Snap to horizontal or vertical
forcelines
flatten bumps on lines
nearlyhvlines
Make nearly horizontal/vertical lines be so
mergelines
Merge adjacent lines into one
setstarttoextrema
Rotate the point list so that the start point is on an extremum
removesingletonpoints
If the contour contains just one point then remove it
stroke ("circular",width[,linecap,linejoin,flags])
("eliptical",width,minor-width,angle
 [,linecap,linejoin,flags])
("caligraphic",width,height,angle[,flags])
Strokes the current line using one of the indicated pens. Line cap may be one of
  • butt
  • round
  • square

line join may be

  • miter
  • round
  • bevel

flags is a tuple containing some of the following strings

  • removeinternal
  • removeexternal
  • cleanup
transform (matrix) Transforms the layer by the matrix
boundingBox () Returns a tuple representing a rectangle (xmin,ymin, xmax,ymax) into which the layer fits. It is not guaranteed to be the smallest such rectangle, but it will often be.
draw (pen) Draw the layer to the pen argument.

glyphPen
This implements the Pen Protocol to draw into a FontForge glyph. You create a glyphPen with the glyphPen attribute of a glyph. You then draw into it with the operators below.
import fontforge;
font = fontforge.open("Ambrosia.sfd");	#Open a font
pen = font["B"].glyphPen();		# Create a pen to draw into glyph "B"
pen.moveTo((100,100));			# draw a square
pen.lineTo((100,200));
pen.lineTo((200,200));
pen.lineTo((200,100));
pen.closePath();			# end the contour

font["A"].draw(pen);			# or you can copy from one glyph to another
					# by having a glyph draw itself into the pen
pen = None;				# Finalize the pen. This tells FontForge
					# that the drawing is done and causes
			                # it to refresh the display (if a UI is active).
Members
None
Methods
method args comments
moveTo ((x,y)) With one exception this call begins every contor and creates an on curve point at (x,y) as the start point of that contour. This should be the first call after a pen has been created and the call that follows a closePath, endPath.
lineTo ((x,y)) Draws a line from the last point to (x,y) and adds that to the contour.
curveTo ((cp1.x,cp1.y),(cp2.x,cp2.y),(x,y))
((cp.x,cp.y),(x,y))
This routine has slightly different arguments depending on the type of the font. When drawing into a cubic font (PostScript) use the first set of arguments (with two control points -- off curve points -- between each on curve point). When drawing into a quadratic font (TrueType) use the second format with one control point between adjacent on-curve points.

The standard appears to support super-bezier curves with more than two control points between on-curve points. FontForge does not. Nor does FontForge allow you to draw a quadratic spline into a cubic font, nor vice versa.

qCurveTo ([(cp.x,cp.y)]*,(x,y))
([(cp.x,cp.y)]*,None))
This routine may only be used in quadratic (TrueType) fonts and has two different formats. It is used to express the TrueType idiom where an on-curve point mid-way between its control points may be omitted, leading to a run of off-curve points (with implied but unspecified on-curve points between them).

The first format allows an arbetary number of off-curve points followed by one on-curve point.

It is possible to have a contour which consists solely of off-curve points. When this happens the contour is NOT started with a moveTo, instead the entire contour, all the off curve points, are listed in one call, and the argument list is terminated by a None to indicate there are no on-curve points.

closePath () Closes the contour (connects the last point to the first point to make a loop) and ends it.
endPath () Ends the contour without closing it. This is only relevant if you are stroking contours.
addComponent (glypn-name,transform) Adds a reference (a component) to the glyph. The PostScript transformation matrix is a 6 element tuple.

glyph
Members
member comments
background The glyph's background layer. This is a copy of the glyph's data. See also foreground.
changed Whether this glyph has been modified. This is (should be) maintained automatically, but you may set it if you wish.
color The color of the glyph in the fontview. A 6 hex-digit RGB number or -1 for default. 0xffffff is white, 0x0000ff is blue, etc.
comment Any comment you wish to associate with the glyph. UTF-8
font The font containing this glyph.
foreground The glyph's foreground layer. This is a copy of the glyph's data. See also background and references.
glyphclass An opentype glyphclass, one of automatic, noclass, baseglyph, baseligature, mark, component
glyphname The name of the glyph
hhints A tuple of all horizontal postscript hints. Each hint is itself a tuple of starting locations and widths.
left_side_bearing The left side bearing of the glyph
originalgid The GID of this glyph in the font it was read from. You may not change this.
references A tuple of tuples containing glyph-name and a transformation matrix for each reference. See also foreground.
right_side_bearing The right side bearing of the glyph
texheight The Tex height
texdepth The Tex depth
ttinstrs Any truetype instructions, returned as a binary string
unicode The glyph's unicode code point, or -1
userdata Whatever you want (contents are not saved in an sfd file)
vhints A tuple of all vertical postscript hints. Each hint is itself a tuple of starting locations and widths.
width The advance width of the glyph. See also vwidth.
vwidth The vertical advance width of the glyph. See also width.
Methods
method args comments
addExtrema ([flags,emsize]) Extrema should be marked by on-curve points. If a curve lacks a point at an extrema this command will add one. Flags may be one of the following strings
all
Add all missing extrema
only_good
Only add extrema on longer splines (with respect to the em-size)
only_good_rm
As above but also merge away on-curve points which are very close to, but not on, an added extremum
addReference (glyph-name[,transform]) Adds a reference to the specified glyph into the current glyph. Optionally specifying a transformation matrix
addHint (is-vertical,start,width) Adds a postscript hint. Takes a boolean flag indicating whether the hint is horizontal or vertical, a start location and the hint's width.
addPosSub (subtable-name,variant)
(subtable-name,variants)
(subtable-name,ligature-components)
(subtable-name,xoff,yoff,xadv,yadv)
(subtable-name,other-glyph-name,  xoff1,yoff1,xadv1,yadv1,
 xoff2,yoff2,xadv2,yadv2)
Adds position/substitution data to the glyph. The number and type of the arguments vary acording to the type of the lookup containing the subtable. The first argument should always be a lookup subtable name. If the lookup is for single substitutions then the second argument should be a string containing a single glyph name. For multiple and alternated substitutions multiple glyph names. For ligatures, a string of the ligature components. For single positionings the second through fifth arguments should be small integers representing the adjustment along that axis. For pairwise positionings (kerning) the second argument should be the name of the other glyph being kerned with, and the third through tenth should be small integers.
autoHint () Generates PostScript hints for this glyph.
autoInstr () Generates (bad) TrueType instructions for this glyph.
autoTrace () Auto traces any background images
boundingBox () Returns a tuple representing a rectangle (xmin,ymin, xmax,ymax) which is the minimum bounding box of the glyph.
build () If the character is a composite character, then clears it and inserts references to its components
canonicalContours () Orders the contours in the current glyph by the x coordinate of their leftmost point. (This can reduce the size of the charstring needed to describe the glyph(s).
canonicalStart () Sets the start point of all the contours of the current glyph to be the leftmost point on the contour. (If there are several points with that value then use the one which is closest to the baseline). This can reduce the size of the charstring needed to describe the glyph(s). By regularizing things it can also make more things available to be put in subroutines.
clear () Clears the contents of the glyph (and marks it as not worth outputting).
cluster ([within,max]) Moves clustered coordinates to a standard central value. See also round.
correctDirection () Orients all contours so that external ones are clockwise and internal counter-clockwise.
exclude (excluded-layer) Removes the excluded area from the current glyph. Takes an argument which is a layer. See also removeOverlap and intersect.
export (filename[,pixelsize,bitdepth]) Uses the file's extension to determine output file type. Exports outline formats to the file. For bitmap formats it will rasterize the glyph and output that. The optional arguments are only used for rasterizing. bitdepth must be 1 or 8.
getPosSub (lookup-subtable-name) Returns any positioning/substitution data attached to the glyph controlled by the lookup-subtable. If the name is "*" then returns data from all subtables.

The data are returned as a tuple of tuples. The first element of the subtuples is the name of the lookup-subtable. The second element will be one of the strings: "Position", "Pair", "Substitution", "AltSubs", "MultSubs","Ligature".

Positioning data will be followed by four small integers representing adjustments to the: x position of the glyph, the y position, the horizontal advance, and the vertical advance.

Pair data will be followed by the name of the other glyph in the pair and then eight small integers representing adjustments to the: x position of the first glyph, the y position, the horizontal advance, and the vertical advance, and then a similar foursome for the second glyph.

Substitution data will be followed by a string containing the name of the glyph to replace the current one.

Multiple and Alternate data will be followed by several strings each containing the name of a replacement glyph.

Ligature data will be followed by several strings each containing the name of a ligature component glyph.

import (filename) Uses the file's extension to determine behavior. Imports outline descriptions (eps, svg, glif files) into the forground layer. Imports image descriptions (bmp, png, xbm, etc.) into the background layer.
intersect () Leaves only areas in the intersection of contours. See also removeOverlap and exclude.
isWorthOutputting () Returns whether the glyph is worth outputting into a font file. Basically a glyph is worth outputting if it contains any contours, or references or has had its width set.
removeOverlap () Removes overlapping areas. See also intersect and exclude.
removePosSub (lookup-subtable-name) Removes all data from the glyph corresponding to the given lookup-subtable. If the name is "*" then all data will be removed.
round ([factor]) Rounds the x and y coordinates of each point in the glyph. If factor is specified then new-coord = round(factor*old-coord)/factor. See also cluster.
selfIntersects () Returns whether any of the contours in this glyph intersects any other contour in the glyph (including itself).
simplify ([error-bound,flags,tan_bounds,
linefixup,linelenmax])
Tries to remove excess points in the glyph if doing so will not perturb the curve by more than error-bound. Flags is a tuple of the following strings
ignoreslopes
Allow slopes to change
ignoreextrema
Allow removal of extrema
smoothcurves
Allow curve smoothing
choosehv
Snap to horizontal or vertical
forcelines
flatten bumps on lines
nearlyhvlines
Make nearly horizontal/vertical lines be so
mergelines
Merge adjacent lines into one
setstarttoextrema
Rotate the point list so that the start point is on an extremum
removesingletonpoints
If the contour contains just one point then remove it
stroke ("circular",width[,linecap,linejoin,flags])
("eliptical",width,minor-width,angle
 [,linecap,linejoin,flags])
("caligraphic",width,height,angle[,flags])
Strokes the contours of the glyph using one of the indicated pens. Line cap may be one of
  • butt
  • round
  • square

line join may be

  • miter
  • round
  • bevel

flags is a tuple containing some of the following strings

  • removeinternal
  • removeexternal
  • cleanup
transform (matrix[,flags]) Transforms the glyph by the matrix. The optional flags argument should be a tuple containing any of the following strings:
  • partialRefs -- Don't transform any references in the glyph, but do transform their offsets. This is useful if the refered glyph will be (or has been) transformed.
  • round -- Round to int after the transformation is done.
unlinkRef ([ref-name]) Unlinks the reference to the glyph named ref-name. If ref-name is omitted, unlinks all references.
unlinkThisGlyph () Unlinks all the references to the current glyph within any other glyph in the font.
draw (pen) Draw the glyph's outline to the pen argument.
glyphPen ([replace=False]) Creates a new glyphPen which will draw into the current glyph. By default the pen will replace any existing contours and references, but setting the optional keyword argument, replace to false will retain the old contents.
Note: Glyphs do not have an independant existance. They live in fonts. You may not create them with new(), only in the context of a font. See font.createChar

selection
This represents a font's selection. You may index it with an encoding value (in the encoding ISO-646-US (ASCII) the character "A" has encoding index 65), or with a glyph's name, or with a string like "uXXXXX" where XXXXX represent the glyphs unicode codepoint in hex, or with a fontforge glyph object.
Members
None
Iterator Protocol
__iter__ () Returns an iterator for the selection which will run all selected glyphs in encoding order. Note if an encoding slot does not contain a glyph it will be skipped.
Methods
method args comments
all () Select everything.
none () Deselect everything.
changed () Select all glyphs which have changed.
invert () Invert the selection.
select (args) There may be an arbetrary number of arguments. Each argument may be either:
  • A glyph name
    Note: There need not be a glyph with this name in the font yet, but if you use a standard name (like "A") fontforge will still know where that glyph should be.
  • An integer (this will be interpreted as either an encoding index or (default) a unicode code point depending on the flags).
  • A fontforge glyph.
  • A tuple of flags.
    (For reasons obscure to me, if I type a single element tuple on the command line, python strips the tuple and leaves me with the element (("more"),"A") => ("more","A"). So if you have only one flag to specify, append a None to the end of the tuple. FF needs the flags to be in a tuple otherwise it can't distinguish them from glyph names)
    unicode
    Interpret integer arguments as unicode code points
    encoding
    Interpret integer arguments as encoding indeces.
    more
    Specified items should be selected
    less
    Specified items should be deselected.
    singletons
    Specified items should be interpreted individually and mean the obvious.
    ranges
    Specified items should be interpreted in pairs and represent all encoding slots between the start and end points specified by the pair. So .select(("ranges",None),"A","Z") would select all the upper case (latin) letters.

If the first argument is not a flag argument (or if it doesn't specify either "more" or "less") then the selection will be cleared. So .select("A") would produce a selection with only "A" selected, .select(("more",None),"A") would add "A" to the current selection, while .select(("less",None),"A") would remove "A" from the current selection.

font
Members
member comments
ascent The font's ascent
bitmapSizes A tuple with an entry for each bitmap strike attached to the font. Each strike is identified by pixelsize (if the strike is a grey scale font it will be indicated by (bitmap-depth<<16)|pixelsize.

When setting this value pass in a tuple of the same format. Any existing strike not specified in the tuple will be removed. Any new sizes will be created (but not rasterized -- use regenBitmaps for that).

changed Bit indicating whether the font has been modified. This is (should be) maintained automatically, but you may set it if you wish.
cidordering
cidregistry
cidsubfontcnt
cidsubfontnames
cidsupplement
cidversion
copyright PostScript copyright notice
cvt Returns a sequence object containing the font's cvt table. Changes made to this object will be made to the font (this is a reference not a copy).
descent The font's descent
design_size Size (in pica points) for which this font was designed.
em The em size of the font. Setting this will scale the entire font to the new size.
encoding The name of the current encoding. Setting it will change the encoding used for indexing
familyname PostScript font family name
fondname Mac fond name
fontname PostScript font name
fullname PostScript font name
gasp Returns a tuple of all gasp table entries. Each item in the tuple is itself a tuple composed of a ppem (an integer) and a tuple of flags. The flags are a chosen from:
  • gridfit
  • antialias
  • symmetric-smoothing
  • gridfit+smoothing
gasp_version The version of the 'gasp' table. Currently this may be 0 or 1.
gpos_lookups Returns a tuple of all positioning lookup names in the font. This member cannot be set.
gsub_lookups Returns a tuple of all substitution lookup names in the font. This member cannot be set.
guide A copy of the font's guide layer
hasvmetrics
hhea_ascent
hhea_ascent_add
hhea_descent
hhea_descent_add
hhea_linegap
is_quadratic Whether the contours should be interpretted as a set of quadratic or cubic splines. Setting this value has the side effect of converting the entire font into the other format
isnew A flag indicating that this is a new font
italicangle
macstyle
maxp_FDEFs The number of function definitions used by the tt program
maxp_IDEFs The number of instruction definitions used by the tt program
maxp_maxStackDepth The maximum stack depth used by the tt program
maxp_storageCnt The number of storage locations used by the tt program
maxp_twilightPtCnt The number of points in the twilight zone of the tt program
maxp_zones The number of zones used in the tt program
multilayer
onlybitmaps A flag indicating that this font only contains bitmaps. No outlines.
os2_family_class
os2_fstype
os2_panose
os2_strikeypos
os2_strikeysize
os2_subxoff
os2_subxsize
os2_subyoff
os2_subysize
os2_supxoff
os2_supxsize
os2_supyoff
os2_supysize
os2_typoascent
os2_typoascent_add
os2_typodescent
os2_typodescent_add
os2_typolinegap
os2_use_typo_metrics
os2_vendor
os2_version
os2_weight
os2_weight_width_slope_only
os2_width
os2_winascent
os2_winascent_add
os2_windescent
os2_windescent_add
private Returns a dictionary like object representing the PostScript private dictionary for the font. Changing entries in this object will change them in the font. (It's a reference, not a copy).

There is an iterator associated with this entry.

selection Returns a reference to an array-like object representing the font's selection. There is one entry for each encoding slot (there may not be a glyph attached to every encoding slot). You may set this with a tuple of integers (or boolean values). There should not be more entries in the tuple than there are encoding slots in the current encoding. A True or non-0 value means the slot is selected.
sfnt_names The strings in the sfnt 'name' table. A tuple of all ms names. Each name is itself a tuple of strings (language,strid,string). Language may be either the (english) name of the language/locale, or the number representing that language in MicroSoft's specification. Strid may be one of the (english) string names (Copyright, Family, SubFamily, etc.) or the numeric value of that item. The string itself is in UTF-8.

Mac names will be automagically created from ms names

size_feature The OpenType 'size' feature has two formats. It may either represent the design size of the font (and nothing else) or the design size, and range (top and bottom point sizes for which this design works), a style id (used to represent this design size throughout the font family) and a set of language/string pairs used to represent this design size in the menu.

If no size information is specified in the font FontForge will return None.

If only the design size is specified, FontForge will return a tuple containing a single element: the point size for which the font was designed. (This is returned as a real number -- the field can represent tenths of a point).

Otherwise FontForge returns a tuple containing five elements, the design size, the bottom of the design range, the top, the style id and a tuple of tuples. Each sub-tuple is a language/string pair. Language may be either the (english) name of the language/locale, or The string itself is in UTF-8.

strokedfont is this a stroked font?
strokewidth the stroke width of a stroked font
uniqueid
upos underline position
userdata Whatever you want (contents are not saved in an sfd file)
uwidth underline width
version PostScript font version string
vertical_origin
vhea_linegap
weight PostScript font weight string
Iterator Protocol
__iter__ () Returns an iterator for the font which will run through the font, in gid order, returning glyph names
<name> in f Returns whether the font contains a glyph with the given name.
Mapping Protocol
len(f) The number of glyph slots in the current encoding
f[i] If i is an integer, then returns the glyph at that encoding. If a string then returns the glyph with that name. May not be assigned to.
Methods
method args comments
new () Creates a new font
addAnchorClass (lookup-subtable-name,
 new-anchor-class-name)
Adds an anchor class to the specified (anchor) subtable.
addKerningClass (lookup-name,new-subtable-name,
 first-classes,
 second-classes,
 offsets
 [,after])
Creates a new subtable and a new kerning class in the named lookup. The classes arguments are tuples of tuples of glyph names (each sub-tuble of glyph names is a kerning class). The offsets argument is a tuple of kerning offsets. There must be as many entries as len(first-class)*len(second-class). The optional after argument is used to specify the order of the subtable within the lookup.
addLookup (new-lookup-name,type,flags,
 feature-script-lang-tuple
 [,after-lookup-name)
Creates a new lookup with the given name, type and flags. It will tag it with any indicated features. The type of one of
  • gsub_single
  • gsub_multiple
  • gsub_alternate
  • gsub_ligature
  • gsub_context
  • gsub_contextchain
  • gsub_revesechain
  • morx_indic
  • morx_context
  • morx_insert
  • gpos_single
  • gpos_pair
  • gpos_cursive
  • gpos_mark2base
  • gpos_mark2ligature
  • gpos_mark2mark
  • gpos_context
  • gpos_contextchain
  • kern_statemachine

The flags argument is a tuple of strings. At most one of these strings may be the name of a mark class. The others are:

  • right_to_left
  • ignore_bases
  • ignore_ligatures
  • ignore_marks

A feature-script-lang tuple is a tuple with one entry for each feature (there may be no entries if there are no features). Each entry is itself a two element tuple, the first entry is a string containing a 4 letter feature tag, and the second entry is another tuple (potentially empty) with an entry for each script for which the feature is active. Each entry here is itself a two element tuple. The first element is a 4 letter script tag and the second is a tuple of languages. Each entry in the language tuple is a four letter language. Example: (("liga",(("latn",("dflt")))))
The optional final argument allows you to specify the ordering of the lookup. If not specified the lookup will be come the first lookup in its table.

addLookupSubtable (lookup-name,
 new-subtable-name
 [,after-subtable-name])
Creates a new subtable within the specified lookup. The optional final argument allows you to specify the ordering within the lookup. If not specified this subtable will be first in the lookup.
alterKerningClass (subtable-name,
 first-classes,
 second-classes,
 offsets)
Changes the kerning class in the named subtable. The classes arguments are tuples of tuples of glyph names (each sub-tuble of glyph names is a kerning class). The offsets argument is a tuple of kerning offsets. There must be as many entries as len(first-class)*len(second-class). The optional after argument is used to specify the order of the subtable within the lookup.
appendSFNTName (language,strid,string) Adds a new (or replaces an old) string in the sfnt 'name' table. Language may be either the english name of the language/locale as a string, or the number representing that language in MicroSoft's specification. Strid may be one of the (english) string names (Copyright, Family, SubFamily, etc.) or the numeric value of that item. The string itself is in UTF-8.
close () Frees memory for the current font.

Warning: Any python pointers to it will become invalid.

compareFonts (other-font,filename,
 flags-tuple)
This will compare the current font with the font in other-font (which must already have been opened). It will write the results to the filename, you may use "-" to send the output to stdout. The flags argument is a tuple of strings and controls what will be compared.
flags
outlines compare outlines
outlines-exactly compare outlines exactly (otherwise allow slight errors and the unlinking of references)
warn-outlines-mismatch warn if the outlines don't exactly match (but are pretty close)
hints compare hints
warn-refs-unlink warn if references need to be unlinked before a match is found
strikes compare bitmap strikes
fontnames compare font names
gpos compare glyph positioning
gsub compare glyph substitutions
add-outlines for any glyphs whose outlines differ, add the outlines of the glyph in the second font to the background of the glyph in the first
create-glyphs if a glyph exists in the second font but not the first, create that glyph in the first and add the outlines from the second into the backgroun layer
createChar (uni[,name]) Create (and return) a character at the specified unicode codepoint in this font and optionally name it. If you wish to create an glyph with no unicode codepoint set the first argument to -1 and specify a name. If there is already a character there, return it (it will not be renamed).
createMappedChar (enc)
(name)
Create (and return) a character at the specified encoding in this font. If there is already a character there, return it
findEncodingSlot (uni)
(name)
Tests whether a glyph with this codepoint or name is in the font's encoding and returns the encoding slot. If the glyph is not present it returns -1.
generate (filename,
 [bitmap_type=,
 flags=,
 bitmap_resolution=,
 subfont_directory=,
 namelist=])
Generates a font. The type is determined by the font's extension.

Flags is a tuple containing some of

afm
output an afm file
pfm
output a pfm file
tfm
output a tfm file
ofm
output a ofm file
composites-in-afm
Store composite info in the afm file
glyph-map-file
Output a glyph map file giving the mapping between output gid and glyphnames
short-post
Do not include glyphnames in a ttf/otf file
apple
output apple advanced typography tables
opentype
output opentype tables
old-kern
output an old style 'kern' with opentype tables
TeX-table
Include a 'TeX ' table in an ttf/otf file
round
Round PS coordinates to integers
no-hints
Do not include PS hints
omit-instructions
Do not include TrueType instructions

See also save().

getKerningClass (subtable-name) Returns a tuple whose entries are: (first-classes, second-classes, offsets). The classes are themselves tuples of tuples of glyph names. The offsets will be a tuple of numeric kerning offsets.
getLookupInfo (lookup-name) Returns a tuple whose entries are: (lookup-type, lookup-flags, feature-script-lang-tuple) The lookup type is a string as described in addLookup, and the feature-script-lang tuple is also described there.
getLookupSubtables (lookup-name) Returns a tuple of all subtable names in that lookup.
getLookupSubtableAnchorClasses (subtable-name) Returns a tuple of all anchor class names in that subtable.
getLookupOfSubtable (subtable-name) Returns the name of the lookup containing this subtable.
getSubtableOfAnchor (anchor-class-name) Returns the name of the subtable containing this anchor class.
interpolateFonts (fraction,filename) Interpolates a font between the current font and the font contained in filename.
isKerningClass (subtable-name) Returns whether the named subtable contains a kerning class.
isVerticalKerning (subtable-name) Returns whether the named subtable contains a vertical kerning data
lookupSetFeatureList (lookup-name,feature-script-lang-tuple) Sets the feature list of indicated lookup. The feature-script-lang tuple is described at addLookup.
lookupSetFlags (lookup-name,flags) Sets the lookup flags for the named lookup.
lookupSetStoreLigatureInAfm (lookup-name,boolean) Sets whether this ligature lookup contains data to store in the afm.
mergeFonts (filename) Merges the font in the file into the current font.
mergeKern (filename) Merge metrics information from the (afm,tfm,etc) file into the current font.
mergeLookups (lookup-name1,lookup-name2) The lookups must be of the same type. All subtables from lookup-name2 will be moved to lookup-name1, the features list of lookup-name2 will be merged with that of lookup-name1, and lookup-name2 will be removed.
mergeLookupSubtables (subtable-name1,subtable-name2) The subtables must be in the same lookup. Not all lookup types allow their subtables to be merged (contextual subtables may not be merged, kerning classes may not be (kerning pairs may be)). Any information bound to subtable2 will be bound to subtable1 and subtable2 will be removed.
print (type,pointsize,
 sample,output-file)
Type is a string which must be one of
fontdisplay
Display all glyphs in the font in encoding order
chars
Display the selected glyphs scaled to fill a page
Ignores the pointsize argument.
waterfall
Displays the selected glyphs at many pointsizes.
The pointsize argument should be a tuple of pointsizes here.
fontsample
The third argument should contain a string which will be layed out and displayed as well as FontForge can.
fontsampleinfile
The third argument should contain the name of a file which contains text to be layed out and displayed.

If output is to a file (see printSetup) then the last argument specifies a file name in which to store output.

regenBitmaps (tuple-of-sizes) A tuple with an entry for each bitmap strike to be regenerated (rerasterized). Each strike is identified by pixelsize (if the strike is a grey scale font it will be indicated by (bitmap-depth<<16)|pixelsize.
removeAnchorClass (anchor-class-name) Removes the named AnchorClass (and all associated points) from the font.
removeLookup (lookup-name) Remove the lookup (and any subtables within it).
removeLookupSubtable (subtable-name) Remove the subtable (and all data associated with it).
removeGlyph (uni[,name])
(glyph)
You may either pass in a FontForge glyph object (from this font) or identify a glyph in the font by unicode code point or name. In any case the glyph will be removed from the font.

WARNING: This frees fontforge's storage to this glyph. If you have any python pointers to that storage they will be looking at garbage. This does not go through the usual python reference mechanism.

save ([filename]) Saves the font to an sfd file. See also generate()
getTableData (table-name) Gets binary data from any saved table. FF will save 'fpgm', 'prep', 'cvt ' and 'maxp'. FF may also save tables which you explicitly request. Do not expect to get binary data for tables like 'GPOS' or 'glyf' which FF will generate when it creates a font... that information is not currently available.

Returns a binary string.

setTableData (table-name,sequence) Sets binary data of any saved table. FF will save 'fpgm', 'prep', 'cvt ' and 'maxp'. FF may also save tables which you explicitly request. Do not expect to set binary data for tables like 'GPOS' or 'glyf' which FF will generate when it creates a font... that information is not currently available.
Selection based interface
See the selection type for how to alter the selection
addExtrema () Extrema should be marked by on-curve points. If a curve in any selected glyph lacks a point at a significant extremum this command will add one.
autoHint () Generates PostScript hints for all selected glyphs.
autoInstr () Generates (bad) TrueType instructions for all selected glyphs.
autoTrace () Auto traces any background images in all selected glyphs
build () If any of the selected characters is a composite character, then this command will clear it and insert references to its components (this command can create new glyphs).
canonicalContours () Orders the contours in the selected glyphs by the x coordinate of their leftmost point. (This can reduce the size of the charstring needed to describe the glyph(s).
canonicalStart () Sets the start point of all the contours of the selected glyphs to be the leftmost point on the contour. (If there are several points with that value then use the one which is closest to the baseline). This can reduce the size of the charstring needed to describe the glyph(s). By regularizing things it can also make more things available to be put in subroutines.
clear () Clears the contents of all selected glyphs
cluster ([within,max]) Moves clustered coordinates to a standard central value in all selected glyphs. See also round.
copy () Copies all selected glyphs into (fontforge's internal) clipboard.
copyReference () Copies all selected glyphs (as references) into (fontforge's internal) clipboard.
correctDirection () Orients all contours so that external ones are clockwise and internal counter-clockwise in all selected glyphs.
cut () Copies all selected glyphs into (fontforge's internal) clipboard. And then clears them.
paste () Pastes the contents of (fontforge's internal) clipboard into the selected glyphs -- and removes what was there before.
intersect () Leaves only areas in the intersection of contours in all selected glyphs. See also removeOverlap.
pasteInto () Pastes the contents of (fontforge's internal) clipboard into the selected glyphs -- and retains what was there before.
removeOverlap () Removes overlapping areas in all selected glyphs. See also intersect.
replaceWithReference ([fudge]) Finds any glyph which contains an inline copy of one of the selected glyphs, and converts that copy into a reference to the appropriate glyph. Selection is changed to the set of glyphs which the command alters.

If specified the fudge argument specifies the error allowed for coordinate differences.

round ([factor]) Rounds the x and y coordinates of each point in all selected glyphs. If factor is specified then new-coord = round(factor*old-coord)/factor. See also cluster.
simplify ([error-bound,flags,tan_bounds,
linefixup,linelenmax])
Tries to remove excess points in all selected glyphs if doing so will not perturb the curve by more than error-bound. Flags is a tuple of the following strings
ignoreslopes
Allow slopes to change
ignoreextrema
Allow removal of extrema
smoothcurves
Allow curve smoothing
choosehv
Snap to horizontal or vertical
forcelines
flatten bumps on lines
nearlyhvlines
Make nearly horizontal/vertical lines be so
mergelines
Merge adjacent lines into one
setstarttoextrema
Rotate the point list so that the start point is on an extremum
removesingletonpoints
If the contour contains just one point then remove it
stroke ("circular",width[,linecap,linejoin,flags])
("eliptical",width,minor-width,angle
 [,linecap,linejoin,flags])
("caligraphic",width,height,angle[,flags])
Strokes the contours of all selected glyphs using one of the indicated pens. Line cap may be one of
  • butt
  • round
  • square

line join may be

  • miter
  • round
  • bevel

flags is a tuple containing some of the following strings

  • removeinternal
  • removeexternal
  • cleanup
transform (matrix) Transforms all selected glyphs by the matrix.
unlinkReferences () Unlinks all references in all selected glyphs and replaces them with splines.

Stupid example

import fontforge                                 #Load the module
amb=fontforge.open("Ambrosia.sfd")               #Open a font
amb.selection.select(("ranges",None),"A","Z")    #select A-Z
amb.copy()                                       #Copy those glyphs into the clipboard

n=fontforge.font()                               #Create a new font
n.selection.select(("ranges",None),"A","Z")      #select A-Z of it
n.paste()                                        #paste the glyphs above in
print n["A"].foreground                          #test to see that something
                                                 #  actually got pasted
n.fontname="NewFont"                             #Give the new font a name
n.save("NewFont.sfd")                            #and save it.