Better script to rewrite pair kerning to class kerning?

I’ve been faced with a not so uncommon scenario: An older fonts file that was started with pair kerning needed its kerning expanded.

I’ve written a script that replaces a single glyph’s pair kerns with class kerns of the same value, e.g. in order to apply the same kerns to other glyphs while retaining the already set kerning values:

import re

# The glyph name which to replace in any pair kerns
glyphname = "space"

# The newly generated and applied kerning classes
classname_left = "space"
classname_right = "space"

gids = {g.id: g for g in Glyphs.font.glyphs}

def glyph_or_class(kern):
    if "@" in kern:
        return kern
    if kern in gids.keys():
        return gids[kern].name


for masterid, left in Glyphs.font.kerning.items():
    print(f"rewrite kerns for layer {masterid}")
    for lkey, vals in left.items():
        leftkern = glyph_or_class(lkey)

        for rkey, val in vals.items():
            rightkern = glyph_or_class(rkey)

            if leftkern == glyphname or rightkern == glyphname:
                print(
                    f"rewrite {leftkern}:{rightkern}: {val} as @MMK_L_{classname_left}:@MMK_R_{classname_right}: {val}"
                )
                Glyphs.font.setKerningForPair(
                    masterid,
                    re.sub(glyphname, "@MMK_L_" + classname_left, leftkern),
                    re.sub(glyphname, "@MMK_R_" + classname_right, rightkern),
                    val,
                )
                Glyphs.font.removeKerningForPair(masterid, leftkern, rightkern)

print(f"set kerning groups {classname_left}|{classname_right} for {glyphname}")
Glyphs.font.glyphs[glyphname].leftKerningGroup = classname_left
Glyphs.font.glyphs[glyphname].rightKerningGroup = classname_right

Is there a better/more intuitive way to do this?

Best,
J

1 Like

Probably a good idea to check if it already exists before you add it.

Oh yea, true. I meant more like along the lines of either a better API to use, or even a feature in the app. For example I didn’t know you can rename kerning groups in the kern panel… would be neat if one could “rename” single pair kerns the same way, to transform them to class kerning.

No, I think it’s good.

You could use “Cleanup” from the action buttin in the Kerning panel.

You mean after?

I meant the “Compress” function, of course.

The difference is that this script compresses kernings for one specific glyph, not indiscriminately all kernings.