Get Active Glyph in FontForge Python

This guide explains how to access the currently active glyph object when writing Python scripts within FontForge. Depending on your workflow, you can retrieve the glyph directly using FontForge's built-in GUI inspection methods or extract it through the active font's current selection state.

Using fontforge.activeGlyph()

The simplest and most direct way to get the active glyph is using the activeGlyph() function provided by the fontforge module. This method works inside the FontForge interactive Python window or when executing scripts via custom menu items while a glyph view window is open.

import fontforge

# Retrieve the active glyph object
glyph = fontforge.activeGlyph()

if glyph is not None:
    print(f"Active Glyph Name: {glyph.glyphname}")
    print(f"Unicode Value: {glyph.unicode}")
else:
    print("No glyph is currently active.")

If no glyph window is currently focused or open, fontforge.activeGlyph() returns None.

Using fontforge.activeFont() and Selections

If you are working from the Font View (the main grid window) rather than an individual Glyph View, activeGlyph() may return None. In this scenario, retrieve the selected glyphs via activeFont():

import fontforge

# Get the currently active font
font = fontforge.activeFont()

if font is not None:
    # Iterate over all currently selected glyphs
    for glyph in font.selection.byGlyphs:
        print(f"Selected Glyph: {glyph.glyphname}")
        
    # Or get the first selected glyph directly
    selected = [g for g in font.selection.byGlyphs]
    if selected:
        primary_glyph = selected[0]
        print(f"Primary Selected Glyph: {primary_glyph.glyphname}")

Context Requirements

These functions rely on an active graphical user interface (GUI) session. If you run a FontForge Python script headlessly from the system command line (e.g., fontforge -script script.py), there is no active GUI context, so activeGlyph() and activeFont() will return None. For command-line scripts, you must explicitly open the font file using fontforge.open("fontfile.sfd") and target glyphs by name or encoding index directly (e.g., font["A"]).