# Scripting 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)

- Scripting functions
- Python Scripting
  - FontForge Modules
    - fontforge
      - Module attributes
        - `hooks`
        - `splineCorner`
        - `splineCurve`
        - `splineHVCurve`
        - `splineTangent`
        - `fontforge.spiroG4`
        - `fontforge.spiroG2`
        - `fontforge.spiroCorner`
        - `fontforge.spiroLeft`
        - `fontforge.spiroRight`
        - `fontforge.spiroOpen`
        - `fontforge.unspecifiedMathValue`
      - Module functions
        - `getPrefs()`
        - `setPrefs()`
        - `hasSpiro()`
        - `savePrefs()`
        - `loadPrefs()`
        - `defaultOtherSubrs()`
        - `readOtherSubrsFile()`
        - `loadEncodingFile()`
        - `loadNamelist()`
        - `loadNamelistDir()`
        - `preloadCidmap()`
        - `printSetup()`
        - `nameFromUnicode()`
        - `UnicodeAnnotationFromLib()`
        - `UnicodeBlockCountFromLib()`
        - `UnicodeBlockEndFromLib()`
        - `UnicodeBlockNameFromLib()`
        - `UnicodeBlockStartFromLib()`
        - `unicodeFromName()`
        - `UnicodeNameFromLib()`
        - `UnicodeNamesListVersion()`
        - `UnicodeNames2FromLib()`
        - `scriptFromUnicode()`
        - `SpiroVersion()`
        - `version()`
        - `loadPlugins()`
        - `getPluginInfo()`
        - `configurePlugins()`
        - `runInitScripts()`
        - `scriptPath()`
        - `fonts()`
        - `activeFont()`
        - `activeGlyph()`
        - `activeLayer()`
        - `fontsInFile()`
        - `open()`
        - `parseTTInstrs()`
        - `unParseTTInstrs()`
        - `unitShape()`
        - `registerGlyphSeparationHook()`
      - User Interface Module Functions
        - `hasUserInterface()`
        - `registerMenuItem()`
        - `registerImportExport()`
        - `logWarning()`
        - `postError()`
        - `postNotice()`
        - `openFilename()`
        - `saveFilename()`
        - `ask()`
        - `askChoices()`
        - `askString()`
        - `askMulti()`
      - Point
        - `point`
        - `point.x`
        - `point.y`
        - `point.on_curve`
        - `point.selected`
        - `point.type`
        - `point.interpolated`
        - `point.name`
        - `point.dup()`
        - `point.transform()`
        - `point.__reduce__()`
      - Contour
        - `contour`
        - `contour.is_quadratic`
        - `contour.closed`
        - `contour.name`
        - `contour.spiros`
        - `contour.dup()`
        - `contour.isEmpty()`
        - `contour.boundingBox()`
        - `contour.getSplineAfterPoint()`
        - `contour.draw()`
        - `contour.__reduce__()`
        - `contour.__iter__()`
        - `contour.moveTo()`
        - `contour.lineTo()`
        - `contour.cubicTo()`
        - `contour.quadraticTo()`
        - `contour.insertPoint()`
        - `contour.makeFirst()`
        - `contour.isClockwise()`
        - `contour.reverseDirection()`
        - `contour.similar()`
        - `contour.xBoundsAtY()`
        - `contour.yBoundsAtX()`
        - `contour.addExtrema()`
        - `contour.cluster()`
        - `contour.merge()`
        - `contour.round()`
        - `contour.selfIntersects()`
        - `contour.simplify()`
        - `contour.transform()`
        - `contour.addInflections()`
        - `contour.balance()`
        - `contour.harmonize()`
      - Layer
        - `layer`
        - `layer.is_quadratic()`
        - `layer.__iter__()`
        - `layer.__reduce__()`
        - `layer.dup()`
        - `layer.isEmpty()`
        - `layer.addExtrema()`
        - `layer.cluster()`
        - `layer.correctDirection()`
        - `layer.export()`
        - `layer.exclude()`
        - `layer.intersect()`
        - `layer.removeOverlap()`
        - `layer.interpolateNewLayer()`
        - `layer.round()`
        - `layer.selfIntersects()`
        - `layer.similar()`
        - `layer.simplify()`
        - `layer.stemControl()`
        - `layer.stroke()`
        - `layer.transform()`
        - `layer.nltransform()`
        - `layer.boundingBox()`
        - `layer.xBoundsAtY()`
        - `layer.yBoundsAtX()`
        - `layer.draw()`
        - `layer.addInflections()`
        - `layer.balance()`
        - `layer.harmonize()`
      - Glyph Pen
        - `glyphPen`
        - `glyphPen.moveTo()`
        - `glyphPen.lineTo()`
        - `glyphPen.curveTo()`
        - `glyphPen.qCurveTo()`
        - `glyphPen.closePath()`
        - `glyphPen.endPath()`
        - `glyphPen.addComponent()`
      - Glyph
        - `glyph`
        - `glyph.activeLayer`
        - `glyph.altuni`
        - `glyph.anchorPoints`
        - `glyph.anchorPointsWithSel`
        - `glyph.background`
        - `glyph.changed`
        - `glyph.color`
        - `glyph.comment`
        - `glyph.dhints`
        - `glyph.encoding`
        - `glyph.font`
        - `glyph.foreground`
        - `glyph.glyphclass`
        - `glyph.glyphname`
        - `glyph.hhints`
        - `glyph.horizontalComponents`
        - `glyph.horizontalComponentItalicCorrection`
        - `glyph.horizontalVariants`
        - `glyph.isExtendedShape`
        - `glyph.italicCorrection`
        - `glyph.layer_cnt`
        - `glyph.layers`
        - `glyph.layerrefs`
        - `glyph.lcarets`
        - `glyph.left_side_bearing`
        - `glyph.manualHints`
        - `glyph.mathKern.bottomLeft`
        - `glyph.mathKern.bottomRight`
        - `glyph.mathKern.topLeft`
        - `glyph.mathKern.topRight`
        - `glyph.originalgid`
        - `glyph.persistent`
        - `glyph.references`
        - `glyph.right_side_bearing`
        - `glyph.script`
        - `glyph.temporary`
        - `glyph.texheight`
        - `glyph.texdepth`
        - `glyph.topaccent`
        - `glyph.ttinstrs`
        - `glyph.unicode`
        - `glyph.unlinkRmOvrlpSave`
        - `glyph.user_decomp`
        - `glyph.userdata`
        - `glyph.vhints`
        - `glyph.validation_state`
        - `glyph.verticalComponents`
        - `glyph.verticalComponentItalicCorrection`
        - `glyph.verticalVariants`
        - `glyph.width`
        - `glyph.vwidth`
        - `glyph.addAnchorPoint()`
        - `glyph.addExtrema()`
        - `glyph.addReference()`
        - `glyph.addHint()`
        - `glyph.addPosSub()`
        - `glyph.appendAccent()`
        - `glyph.autoHint()`
        - `glyph.autoInstr()`
        - `glyph.autoTrace()`
        - `glyph.boundingBox()`
        - `glyph.build()`
        - `glyph.canonicalContours()`
        - `glyph.canonicalStart()`
        - `glyph.changeWeight()`
        - `glyph.condenseExtend()`
        - `glyph.clear()`
        - `glyph.cluster()`
        - `glyph.correctDirection()`
        - `glyph.doUndoLayer()`
        - `glyph.exclude()`
        - `glyph.export()`
        - `glyph.genericGlyphChange()`
        - `glyph.getPosSub()`
        - `glyph.importOutlines()`
        - `glyph.intersect()`
        - `glyph.isWorthOutputting()`
        - `glyph.preserveLayerAsUndo()`
        - `glyph.removeOverlap()`
        - `glyph.removePosSub()`
        - `glyph.round()`
        - `glyph.selfIntersects()`
        - `glyph.setLayer()`
        - `glyph.simplify()`
        - `glyph.stroke()`
        - `glyph.transform()`
        - `glyph.nltransform()`
        - `glyph.unlinkRef()`
        - `glyph.unlinkThisGlyph()`
        - `glyph.useRefsMetrics()`
        - `glyph.validate()`
        - `glyph.draw()`
        - `glyph.glyphPen()`
        - `glyph.addInflections()`
        - `glyph.balance()`
        - `glyph.harmonize()`
      - Selection
        - `selection`
        - `selection.byGlyphs`
        - `selection.__iter__()`
        - `selection.all()`
        - `selection.none()`
        - `selection.changed()`
        - `selection.invert()`
        - `selection.select()`
      - Private
        - `private`
        - `private.__iter__()`
        - `private.guess()`
      - Math
        - `math.ScriptPercentScaleDown`
        - `math.ScriptScriptPercentScaleDown`
        - `math.DelimitedSubFormulaMinHeight`
        - `math.DisplayOperatorMinHeight`
        - `math.MathLeading`
        - `math.AxisHeight`
        - `math.AccentBaseHeight`
        - `math.FlattenedAccentBaseHeight`
        - `math.SubscriptShiftDown`
        - `math.SubscriptTopMax`
        - `math.SubscriptBaselineDropMin`
        - `math.SuperscriptShiftUp`
        - `math.SuperscriptShiftUpCramped`
        - `math.SuperscriptBottomMin`
        - `math.SuperscriptBaselineDropMax`
        - `math.SubSuperscriptGapMin`
        - `math.SuperscriptBottomMaxWithSubscript`
        - `math.SpaceAfterScript`
        - `math.UpperLimitGapMin`
        - `math.UpperLimitBaselineRiseMin`
        - `math.LowerLimitGapMin`
        - `math.LowerLimitBaselineDropMin`
        - `math.StackTopShiftUp`
        - `math.StackTopDisplayStyleShiftUp`
        - `math.StackBottomShiftDown`
        - `math.StackBottomDisplayStyleShiftDown`
        - `math.StackGapMin`
        - `math.StackDisplayStyleGapMin`
        - `math.StretchStackTopShiftUp`
        - `math.StretchStackBottomShiftDown`
        - `math.StretchStackGapAboveMin`
        - `math.StretchStackGapBelowMin`
        - `math.FractionNumeratorShiftUp`
        - `math.FractionNumeratorDisplayStyleShiftUp`
        - `math.FractionDenominatorShiftDown`
        - `math.FractionDenominatorDisplayStyleShiftDown`
        - `math.FractionNumeratorGapMin`
        - `math.FractionNumeratorDisplayStyleGapMin`
        - `math.FractionRuleThickness`
        - `math.FractionDenominatorGapMin`
        - `math.FractionDenominatorDisplayStyleGapMin`
        - `math.SkewedFractionHorizontalGap`
        - `math.SkewedFractionVerticalGap`
        - `math.OverbarVerticalGap`
        - `math.OverbarRuleThickness`
        - `math.OverbarExtraAscender`
        - `math.UnderbarVerticalGap`
        - `math.UnderbarRuleThickness`
        - `math.UnderbarExtraDescender`
        - `math.RadicalVerticalGap`
        - `math.RadicalDisplayStyleVerticalGap`
        - `math.RadicalRuleThickness`
        - `math.RadicalExtraAscender`
        - `math.RadicalKernBeforeDegree`
        - `math.RadicalKernAfterDegree`
        - `math.RadicalDegreeBottomRaisePercent`
        - `math.MinConnectorOverlap`
        - `math.exists()`
        - `math.clear()`
      - Font
        - `font`
        - `font.activeLayer`
        - `font.ascent`
        - `font.bitmapSizes`
        - `font.capHeight`
        - `font.changed`
        - `font.cidcopyright`
        - `font.cidfamilyname`
        - `font.cidfontname`
        - `font.cidfullname`
        - `font.cidordering`
        - `font.cidregistry`
        - `font.cidsubfont`
        - `font.cidsubfontcnt`
        - `font.cidsubfontnames`
        - `font.cidsupplement`
        - `font.cidversion`
        - `font.cidweight`
        - `font.comment`
        - `font.copyright`
        - `font.cvt`
        - `font.default_base_filename`
        - `font.descent`
        - `font.design_size`
        - `font.em`
        - `font.encoding`
        - `font.familyname`
        - `font.fondname`
        - `font.fontlog`
        - `font.fontname`
        - `font.fullname`
        - `font.gasp`
        - `font.gasp_version`
        - `font.gpos_lookups`
        - `font.gsub_lookups`
        - `font.guide`
        - `font.hasvmetrics`
        - `font.head_optimized_for_cleartype`
        - `font.hhea_ascent`
        - `font.hhea_ascent_add`
        - `font.hhea_descent`
        - `font.hhea_descent_add`
        - `font.hhea_linegap`
        - `font.horizontalBaseline`
        - `font.is_cid`
        - `font.is_quadratic`
        - `font.isnew`
        - `font.italicangle`
        - `font.macstyle`
        - `font.layer_cnt`
        - `font.layers`
        - `font.loadState`
        - `font.maxp_FDEFs`
        - `font.maxp_IDEFs`
        - `font.maxp_maxStackDepth`
        - `font.maxp_storageCnt`
        - `font.maxp_twilightPtCnt`
        - `font.maxp_zones`
        - `font.multilayer`
        - `font.onlybitmaps`
        - `font.os2_codepages`
        - `font.os2_family_class`
        - `font.os2_fstype`
        - `font.os2_stylemap`
        - `font.os2_panose`
        - `font.os2_strikeypos`
        - `font.os2_strikeysize`
        - `font.os2_subxoff`
        - `font.os2_subxsize`
        - `font.os2_subyoff`
        - `font.os2_subysize`
        - `font.os2_supxoff`
        - `font.os2_supxsize`
        - `font.os2_supyoff`
        - `font.os2_supysize`
        - `font.os2_typoascent`
        - `font.os2_typoascent_add`
        - `font.os2_typodescent`
        - `font.os2_typodescent_add`
        - `font.os2_typolinegap`
        - `font.os2_use_typo_metrics`
        - `font.os2_unicoderanges`
        - `font.os2_vendor`
        - `font.os2_version`
        - `font.os2_weight`
        - `font.os2_weight_width_slope_only`
        - `font.os2_width`
        - `font.os2_winascent`
        - `font.os2_winascent_add`
        - `font.os2_windescent`
        - `font.os2_windescent_add`
        - `font.path`
        - `font.persistent`
        - `font.math`
        - `font.private`
        - `font.privateState`
        - `font.selection`
        - `font.sfd_path`
        - `font.sfnt_names`
        - `font.sfntRevision`
        - `font.size_feature`
        - `font.strokedfont`
        - `font.strokewidth`
        - `font.temporary`
        - `font.texparameters`
        - `font.uniqueid`
        - `font.upos`
        - `font.userdata`
        - `font.uwidth`
        - `font.version`
        - `font.verticalBaseline`
        - `font.vertical_origin`
        - `font.vhea_linegap`
        - `font.weight`
        - `font.woffMajor`
        - `font.woffMinor`
        - `font.woffMetadata`
        - `font.xHeight`
        - `font.__iter__()`
        - `font.__contains__()`
        - `font.__len__()`
        - `font.__getitem__()`
        - `font.addAnchorClass()`
        - `font.addKerningClass()`
        - `font.addLookup()`
        - `font.addLookupSubtable()`
        - `font.addContextualSubtable()`
        - `font.addSmallCaps()`
        - `font.alterKerningClass()`
        - `font.autoKern()`
        - `font.appendSFNTName()`
        - `font.buildOrReplaceAALTFeatures()`
        - `font.cidConvertByCMap()`
        - `font.cidConvertTo()`
        - `font.cidFlatten()`
        - `font.cidFlattenByCMap()`
        - `font.cidInsertBlankSubFont()`
        - `font.cidRemoveSubFont()`
        - `font.close()`
        - `font.compareFonts()`
        - `font.createChar()`
        - `font.createInterpolatedGlyph()`
        - `font.createMappedChar()`
        - `font.find()`
        - `font.findEncodingSlot()`
        - `font.glyphs()`
        - `font.generate()`
        - `font.generateTtc()`
        - `font.generateFeatureFile()`
        - `font.genericGlyphChange()`
        - `font.getKerningClass()`
        - `font.getLookupInfo()`
        - `font.getLookupSubtables()`
        - `font.getLookupSubtableAnchorClasses()`
        - `font.getLookupOfSubtable()`
        - `font.getSubtableOfAnchor()`
        - `font.importBitmaps()`
        - `font.importLookups()`
        - `font.interpolateFonts()`
        - `font.isKerningClass()`
        - `font.isVerticalKerning()`
        - `font.italicize()`
        - `font.lookupSetFeatureList()`
        - `font.lookupSetFlags()`
        - `font.lookupSetStoreLigatureInAfm()`
        - `font.mergeFonts()`
        - `font.mergeFeature()`
        - `font.mergeKern()`
        - `font.mergeLookups()`
        - `font.mergeLookupSubtables()`
        - `font.printSample()`
        - `font.randomText()`
        - `font.regenBitmaps()`
        - `font.removeAnchorClass()`
        - `font.removeLookup()`
        - `font.removeLookupSubtable()`
        - `font.removeGlyph()`
        - `font.replaceAll()`
        - `font.revert()`
        - `font.revertFromBackup()`
        - `font.save()`
        - `font.saveNamelist()`
        - `font.getTableData()`
        - `font.setTableData()`
        - `font.validate()`
        - `font.addExtrema()`
        - `font.addInflections()`
        - `font.autoHint()`
        - `font.autoInstr()`
        - `font.autoWidth()`
        - `font.autoTrace()`
        - `font.build()`
        - `font.canonicalContours()`
        - `font.canonicalStart()`
        - `font.changeWeight()`
        - `font.condenseExtend()`
        - `font.clear()`
        - `font.cluster()`
        - `font.copy()`
        - `font.copyReference()`
        - `font.correctDirection()`
        - `font.correctReferences()`
        - `font.cut()`
        - `font.paste()`
        - `font.intersect()`
        - `font.pasteInto()`
        - `font.removeOverlap()`
        - `font.replaceWithReference()`
        - `font.round()`
        - `font.simplify()`
        - `font.stroke()`
        - `font.transform()`
        - `font.nltransform()`
        - `font.unlinkReferences()`
    - psMat
      - `identity()`
      - `compose()`
      - `inverse()`
      - `rotate()`
      - `scale()`
      - `skew()`
      - `translate()`
  - Command line convenience
  - Trivial example
  - FontForge as a python extension

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

## Scripting Language

Note

This section covers FontForge’s native scripting functionality.

For the Python scripting functionality, see here.

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

- A variable name (like “$1” or “i” or “@fontvar” or “_global”)

  The scope of the variable depends on the initial character of its name.

  - A ‘$’ signifies that it is a built-in variable. The user cannot create any new variables beginning with ‘$’. Some, but not all, of these may be assigned to.

  - A ‘_’ signifies that the variable is global, it is always available. You can use these to store context across different script files (or to access data within nested script files).

  - A ‘@’ signifies that the variable is associated with the font. Any two scripts looking at the same font will have access to the same variables.

  - A variable which begins with a letter is a local variable. It is only meaningful within the current script file. Nested script files may have different variables with the same names.

- an integer expressed in decimal, hex or octal

- a unicode code point (which has a prefix of “0u” or “0U” and is followed by a string of hex digits. This is only used by the select command.

- a real number (in “C” locale format – “.” as the decimal point character)

- A string which may be enclosed in either double or single quotes. String tokens are limited to 256 bytes. “n” can be used to represent a newline character. (If you need longer strings use the concatenation operator).

- a procedure to call or file to invoke.

- an expression within parentheses

- a series of expressions (separated by commas) within brackets, as `[1, 2, 3, 5, 8]`, used to create an array.

There are three different comments supported:

- Starting with a “#” character and proceeding to end of line

- Starting with “//” and proceeding to end of line

- Starting with “/” and proceeding to “/”

### Expressions

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:

- unary operators (+, -, !, ~, ++ (prefix and postfix), –(prefix and postfix), () (procedure call), [] (array index), :h, :t, :r, :e

  Most of these are as expected in C, the last four are borrowed from shell scripts and are applied to strings

  - :h gives the head (directory) of a pathspec

  - :t gives the tail (filename) of a pathspec

  - :r gives the pathspec without the extension (if any)

  - :e gives the extension

- *, /, % (binary multiplicative operators)

- +, - (binary arithmetic operators)

  If the first operand of + is a string then + will be treated as concatenation rather than addition. If the second operand is a number it will be converted to a string (decimal representation) and then concatenated. If the first operand of + is an array then + will do array concatenation – if the second argument is also an array the two will be concatenated ([1,2] + [3,4] yields [1,2,3,4], while [1,2] + 3 yields [1,2,3]). Otherwise these are the normal arithmetric operations.

- ==, !=, >, <, >=, <= (comparison operators, may be applied to either two integers or two strings)

- &&, & (logical and, bitwise and. (logical and will do short circuit evaluation))

- ||, |, ^ (logical or, bitwise or, bitwise exclusive or (logical or will do short circuit evaluation))

- =, +=, -=, *=, /=, %= (assignment operators as in C. The += will act as concatenation if the first operand is a string.)

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. As a convenience, it is not necessary to include the script’s extension if it is either “.ff” or “.pe”. 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

- an expression

-     if ( expression )
          statements
      {elseif ( expression )
          statements}
      [else
          statements]
      endif

-     while ( expression )
          statements
      endloop

-     foreach
          statements
      endloop

- `break`

- `return [ expression ]`

- `shift`

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.

### Variables

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

$0

  the current script filename

$1
$2
$n

  the first, second (…) argument to the script file

$argc

  the number of arguments passed to the script file (this will always be at least 1 as $0 is always present)

$argv

  allows you to access the array of all the arguments

$curfont

  the name of the filename in which the current font resides

$firstfont

  the name of the filename of the font which is first on the font list (Can be used by `Open()`), if there are no fonts loaded this returns an empty string. This can be used to determine if any font at all is loaded into fontforge.

$nextfont

  the name of the filename of the font which follows the current font on the list (or the empty string if the current font is the last one on the list)

$fontchanged

  returns 1 if the current font has changed, 0 if it has not changed since it was read in (or saved).

$fontname

  the name contained in the postscript FontName field

$familyname

  the name contained in the postscript FamilyName field

$fullname

  the name contained in the postscript FullName field

$fondname

  if set this name indicates what FOND the current font should be put in under Generate Mac Family.

$weight

  the name contained in the postscript Weight field

$copyright

  the name contained in the postscript Notice field

$filename

  the name of the file containing the font.

$fontversion

  the string containing the font’s version

$iscid

  1 if the current font is a cid keyed font, 0 if not

$cidfontname

  returns the fontname of the top-level cid-keyed font (or the empty string if there is none)

  Can be used to detect if this is a cid keyed font.

$cidfamilyname, $cidfullname, $cidweight, $cidcopyright

  similar to `cidfontname`

$mmcount

  returns 0 for non multiple master fonts, returns the number of instances in a multiple master font.

$italicangle

  the value of the postscript italic angle field

$loadState

  a bitmask of non-fatal errors encountered when loading the font.

$privateState

  a bitmask of some errors in the PostScript Private dictionary (see `fontforge.font.privateState` for more info).

$curcid

  returns the fontname of the current font

$firstcid

  returns the fontname of the first font within this cid font

$nextcid

  returns the fontname of the next font within this cid font (or the empty string if the current sub-font is the last)

$macstyle

  returns the value of the macstyle field (a set of bits indicating whether the font is bold, italic, condensed, etc.)

$bitmaps

  returns an array containing all bitmap pixelsizes generated for this font. (If the font database contains greymaps then they will be indicated in the array as `(<BitmapDepth><<16)|<PixelSize>`)

$order

  returns an integer containing either 2 (for truetype fonts) or 3 (for postscript fonts). This indicates whether the font uses quadratic or cubic splines.

$em

  returns the number of em-units used by the font.

$ascent

  returns the ascent of the font

$descent

  returns the descent of the font.

$selection

  returns an array containing one entry for each glyph in the current font indicating whether that glyph is selected or not (0=>not, 1=>selected)

$panose

  returns an array containing the 10 panose values for the font.

$trace

  if this is set to one then FontForge will trace each procedure call.

$version
  returns a string containing the current version of fontforge. This

    should look something like “20050817”.

$haspython

  returns 1 if python scripting is available, 0 if it is not.

### Preferences

- `$<Preference Item>` (for example `$AutoHint`) allows you to examine the value of that preference item (to set it use `SetPref()`)

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

- Built-in procedures that do not require a font

- File menu

- File manipulation

- Edit menu

- Select menu

- Element menu

- Font information

- Glyph information

- Advanced Typography

- Encoding menu

- Hint menu

- Metrics menu

- Multiple master

- CID keyed fonts

- User interaction

- Preferences

- Math

- Unicode

- String manipulation

- Character manipulation

- Arrays

- Miscellaneous

- Deprecated Names

### Built-in procedures in alphabetic order

### Built-in procedures that do not require a loaded font

- `Array()`

- `AskUser()`

- `ATan2()`

- `Ceil()`

- `Chr()`

- `Cos()`

- `Floor()`

- `Error()`

- `Exp()`

- `DefaultOtherSubrs()`

- `FileAccess()`

- `FontsInFile()`

- `GetEnv()`

- `GetPref()`

- `Int()`

- `IsAlNum()`

- `IsAlpha()`

- `IsDigit()`

- `IsFinite()`

- `IsHexDigit()`

- `IsLower()`

- `IsNan()`

- `IsSpace()`

- `IsUpper()`

- `LoadEncodingFile()`

- `LoadNamelist()`

- `LoadNamelistDir()`

- `LoadPrefs()`

- `LoadStringFromFile()`

- `Log()`

- `NameFromUnicode()`

- `New()`

- `Open()`

- `Ord()`

- `PostNotice()`

- `Pow()`

- `PreloadCidmap()`

- `Print()`

- `Rand()`

- `ReadOtherSubrsFile()`

- `Real()`

- `Round()`

- `SavePrefs()`

- `SetPref()`

- `SizeOf()`

- `Sin()`

- `Sqrt()`

- `Strcasestr()`

- `Strcasecmp()`

- `Strftime()`

- `StrJoin()`

- `Strlen()`

- `Strrstr()`

- `Strskipint()`

- `StrSplit()`

- `Strstr()`

- `Strsub()`

- `Strtod()`

- `Strtol()`

- `Tan()`

- `ToLower()`

- `ToMirror()`

- `ToString()`

- `ToUpper()`

- `TypeOf()`

- `UCodePoint()`

- `UnicodeFromName()`

- `Ucs4()`

- `Utf8()`

- `WriteStringToFile()`

### Built-in procedures that act like the File Menu

- `Close()`

- `Export()`

- `FontsInFile()`

- `Generate()`

- `GenerateFamily()`

- `Import()`

- `MergeKern()` deprecated

- `MergeFeature()`

- `New()`

- `Open()`

- `PrintFont()`

- `PrintSetup()`

- `Quit()`

- `Revert()`

- `RevertToBackup()`

- `Save()`

### File Manipulation

- `FileAccess()`

- `FontImage()`

- `LoadStringFromFile()`

- `WriteStringToFile()`

### Built-in procedures that act like the Edit Menu

- `Clear()`

- `ClearBackground()`

- `Copy()`

- `CopyAnchors()`

- `CopyFgToBg()`

- `CopyLBearing()`

- `CopyRBearing()`

- `CopyReference()`

- `CopyUnlinked()`

- `CopyVWidth()`

- `CopyWidth()`

- `Cut()`

- `Join()`

- `Paste()`

- `Paste()`

- `PasteWithOffset()`

- `ReplaceWithReference()`

- `SameGlyphAs()`

- `UnlinkReference()`

### Built-in procedures that act like the Select Menu

- `Select()`

- `SelectAll()`

- `SelectAllInstancesOf()`

- `SelectBitmap()`

- `SelectByPosSub()`

- `SelectChanged()`

- `SelectFewer()`

- `SelectFewerSingletons()`

- `SelectGlyphsBoth()`

- `SelectGlyphsReferences()`

- `SelectGlyphsSplines()`

- `SelectHintingNeeded()`

- `SelectIf()`

- `SelectInvert()`

- `SelectMore()`

- `SelectMoreIf()`

- `SelectMoreSingletons()`

- `SelectMoreSingletonsIf()`

- `SelectNone()`

- `SelectSingletons()`

- `SelectSingletonsIf()`

- `SelectWorthOutputting()`

### Built-in procedures that act like the Element Menu

- `AddAccent()`

- `AddExtrema()`

- `AddInflections()`

- `ApplySubstitution()`

- `AutoTrace()`

- `Balance()`

- `BitmapsAvail()`

- `BitmapsRegen()`

- `BuildAccented()`

- `BuildComposite()`

- `BuildDuplicate()`

- `CanonicalContours()`

- `CanonicalStart()`

- `ChangeWeight()`

- `CompareFonts()`

- `CompareGlyphs()`

- `CorrectDirection()`

- `DefaultRoundToGrid()`

- `DefaultUseMyMetrics()`

- `ExpandStroke()`

- `FindIntersections()`

- `Harmonize()`

- `HFlip()`

- `Inline()`

- `InterpolateFonts()`

- `Italic()`

- `MergeFonts()`

- `Move()`

- `MoveReference()`

- `NearlyHvCps()`

- `NearlyHvLines()`

- `NearlyLines()`

- `NonLinearTransform()`

- `Outline()`

- `OverlapIntersect()`

- `PositionReference()`

- `RemoveOverlap()`

- `Rotate()`

- `RoundToCluster()`

- `RoundToInt()`

- `Scale()`

- `ScaleToEm()`

- `Shadow()`

- `Simplify()`

- `Skew()`

- `SmallCaps()`

- `Transform()`

- `VFlip()`

- `Wireframe()`

### Font Info

- `AddSizeFeature()`

- `ChangePrivateEntry()`

- `ClearPrivateEntry()`

- `GetFontBoundingBox()`

- `GetMaxpValue()`

- `GetOS2Value()`

- `GetPrivateEntry()`

- `GetTeXParam()`

- `GetTTFName()`

- `HasPrivateEntry()`

- `ScaleToEm()`

- `SetFondName()`

- `SetFontHasVerticalMetrics()`

- `SetFontNames()`

- `SetFontOrder()`

- `SetGasp()`

- `SetItalicAngle()`

- `SetMacStyle()`

- `SetMaxpValue()`

- `SetOS2Value()`

- `SetPanose()`

- `SetTeXParams()`

- `SetTTFName()`

- `SetUniqueID()`

- Some items (such as the font name) may be retrieved via built-in variables.

### Glyph Info

- `DrawsSomething()`

- `GetPosSub()`

- `GlyphInfo()`

- `SetGlyphColor()`

- `SetGlyphComment()`

- `SetGlyphChanged()`

- `SetGlyphClass()`

- `SetGlyphName()`

- `SetUnicodeValue()`

- `SetGlyphTeX()`

- `WorthOutputting()`

### Built-in procedures that handle Advanced Typography

- `AddAnchorClass()`

- `AddAnchorPoint()`

- `AddLookup()`

- `AddLookupSubtable()`

- `AddPosSub()`

- `AddSizeFeature()`

- `ApplySubstitution()`

- `CheckForAnchorClass()`

- `GetAnchorPoints()`

- `GetLookupInfo()`

- `GetLookups()`

- `GetLookupSubtables()`

- `GetLookupOfSubtable()`

- `GetPosSub()`

- `GetSubtableOfAnchor()`

- `GenerateFeatureFile()`

- `HasPreservedTable()`

- `LoadTableFromFile()`

- `LookupStoreLigatureInAfm()`

- `LookupSetFeatureList()`

- `MergeLookups()`

- `MergeLookupSubtables()`

- `RemoveAnchorClass()`

- `RemoveLookup()`

- `RemoveLookupSubtable()`

- `RemovePosSub()`

- `RemovePreservedTable()`

- `SaveTableToFile()`

### Built-in procedures that act like the Encoding Menu

- `CharCnt()`

- `DetachGlyphs()`

- `DetachAndRemoveGlyphs()`

- `LoadEncodingFile()`

- `MultipleEncodingsToReferences()`

- `Reencode()`

- `RemoveDetachedGlyphs()`

- `RenameGlyphs()`

- `SameGlyphAs()`

- `SetCharCnt()`

### Built-in procedures that act like the Hint Menu

- `AddDHint()`

- `AddHHint()`

- `AddInstrs()`

- `AddVHint()`

- `AutoCounter()`

- `AutoHint()`

- `AutoInstr()`

- `ChangePrivateEntry()`

- `ClearGlyphCounterMasks()`

- `ClearHints()`

- `ClearInstrs()`

- `ClearPrivateEntry()`

- `ClearTable()`

- `DontAutoHint()`

- `FindOrAddCvtIndex()`

- `GetCvtAt()`

- `GetPrivateEntry()`

- `HasPrivateEntry()`

- `ReplaceGlyphCounterMasks()`

- `ReplaceCvtAt()`

- `SetGlyphCounterMask()`

- `SubstitutionPoints()`

### Built-in procedures that act like the Metrics Menu

- `AutoKern()`

- `AutoWidth()`

- `CenterInWidth()`

- `SetKern()`

- `RemoveAllKerns()`

- `RemoveAllVKerns()`

- `SetLBearing()`

- `SetRBearing()`

- `SetVKern()`

- `SetVWidth()`

- `SetWidth()`

- `VKernFromHKern()`

### Multiple master routines

- `MMAxisBounds()`

- `MMAxisNames()`

- `MMBlendToNewFont()`

- `MMChangeInstance()`

- `MMChangeWeight()`

- `MMInstanceNames()`

- `MMWeightedName()`

### CID routines

- `CIDChangeSubFont()`

- `CIDFlatten()`

- `CIDFlattenByCMap()`

- `CIDSetFontNames()`

- `ConvertToCID()`

- `ConvertByCMap()`

- `PreloadCidmap()`

### User Interaction

- `AskUser()`

- `Error()`

- `PostNotice()`

- `Print()`

### Preferences

- `DefaultOtherSubrs()`

- `GetPref()`

- `LoadEncodingFile()`

- `LoadNamelist()`

- `LoadNamelistDir()`

- `LoadPrefs()`

- `ReadOtherSubrsFile()`

- `SavePrefs()`

- `SetPref()`

- It it also possible to get the value of a preference item by preceding its name with a dollar sign.

### Math

- `ATan2()`

- `Ceil()`

- `Chr()`

- `Cos()`

- `Exp()`

- `Floor()`

- `Int()`

- `IsFinite()`

- `IsNan()`

- `Log()`

- `Ord()`

- `Pow()`

- `Rand()`

- `Real()`

- `Round()`

- `Sin()`

- `Sqrt()`

- `Strskipint()`

- `Strtod()`

- `Strtol()`

- `Tan()`

- `ToString()`

- `UCodePoint()`

### Unicode

- `NameFromUnicode()`

- `UCodePoint()`

- `UnicodeFromName()`

- `Ucs4()`

- `Utf8()`

### String manipulation

- `Chr()`

- `GetEnv()`

- `NameFromUnicode()`

- `Ord()`

- `Strcasecmp()`

- `Strcasestr()`

- `Strftime()`

- `StrJoin()`

- `Strlen()`

- `Strrstr()`

- `Strskipint()`

- `StrSplit()`

- `Strstr()`

- `Strsub()`

- `Strtod()`

- `Strtol()`

- `ToString()`

- `UnicodeFromName()`

- `Ucs4()`

- `Utf8()`

### Character Manipulation

- `IsAlNum()`

- `IsAlpha()`

- `IsDigit()`

- `IsHexDigit()`

- `IsLower()`

- `IsSpace()`

- `IsUpper()`

- `ToLower()`

- `ToMirror()`

- `ToUpper()`

### Arrays

- `Array()`

- `SizeOf()`

### Miscellaneous

- `InFont()`

- `TypeOf()`

### Deprecated Names

- `ClearGlyphCounterMasks()`

- `GlyphInfo()`

- `ReplaceGlyphCounterMasks()`

- `SetGlyphColor()`

- `SetGlyphComment()`

- `SetGlyphCounterMask()`

- `SetGlyphName()`

## Examples

- FontForge’s testsuite in the test subdirectory (such as it is)

- Directory of donated scripts

- Scripts used in other projects

  - x-symbol

- the scripting tutorial

### 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.activeFont()`).

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.