◐ Shell
clean mode source ↗

Fix mathtext font fallback for glyphs missing from math fonts by 1wos · Pull Request #31766 · matplotlib/matplotlib

PR summary

Closes #29173.

CJK characters render correctly in regular text but are replaced by a ¤
placeholder when they appear inside a math expression ($...$). The cause is
that mathtext has no glyph-level font fallback: when a character is missing from
the math font (and the STIX/Bakoma math fallbacks), UnicodeFonts._get_glyph
returns a dummy glyph, whereas regular text walks the font's fallback chain.

This change makes _get_glyph search the configured text fonts and their
fallback chain (the same ones regular text uses, ending in the Last Resort font)
before falling back to the dummy glyph. The search only runs when the glyph is
missing, so text that already renders is unaffected. The FT2Font fallback list is
exposed to Python as a private FT2Font._fallbacks property to support this.

With a CJK font configured, CJK characters render in math just like in regular
text; otherwise they fall back to the Last Resort font instead of the dummy.

import matplotlib.pyplot as plt
plt.rcParams["font.family"] = "Arial Unicode MS"  # any CJK-capable font
plt.text(0.5, 0.5, r"$\alpha + 中文 + 한글 + \beta$")
plt.show()

AI Disclosure

I used generative AI (Claude) to help dig through the font code and draft the
implementation, tests, and this description. I reported the issue, decided on the
approach, and reviewed and tested everything locally.

PR checklist