GNU TeXmacsUser manualReferenceAboutEnglish
The font selection algorithm

1.From the environment to a font

The typesetter recomputes its current font in edit_env_rep::update_font (

Typeset/Env/env_semantics.cpp

) whenever an environment variable of type Env_Font or Env_Font_Size changes, as well as on changes of the mode, the magnification or the script level. The size is font-base-size times font-size, reduced for scripts by get_script_size. Then, depending on the mode (edit_env_rep::make_current_font):

When the resulting font carries an OpenType MATH table and the script level is positive, the size is recomputed from the percentages of the table (script_percent, script_script_percent), unless math-font-sizes is set, and an untuned OpenType math font is shown through its ssty feature (feature_font); see mathematics from the MATH table. Finally, if font-features is not empty, the result is wrapped by apply_features (see OpenType features), and if font-effects is not empty, by apply_effects. The ten argument variant of smart_font reduces to the six argument one: if the preference "new style fonts" is disabled, it directly returns find_font applied to its first four arguments; otherwise it uses the second group of arguments, except that a text font roman is replaced by the first family, the math variants ms and mt are mapped to ss and tt, a series other than medium of the first group replaces the text series (so that math-font-series reaches the math font), and the shape right is mapped to mathupright.

The six argument smart_font calls smart_font_bis. When the variant is not rm and resolves to another physical family than the rm variant, the resulting font is magnified so that its x-height matches the x-height of the rm font. In smart_font_bis:

The construction of the smart font itself, and the meaning of the comma separated family lists, are described in the chapter on smart fonts. The rest of this chapter describes closest_font and the functions it relies on.

2.Features and logical fonts

2.1.Kinds of features

A feature is a lower case word. The predicates in

Graphics/Fonts/font_select.cpp

classify features into the following kinds; two features are of the same kind (same_kind) if they belong to the same row. The last column gives the default value, which is assumed when a font does not mention any feature of that kind.

Kind Predicate Values Default
stretch is_stretch …condensed, …unextended, …wide, …caption unextended
weight is_weight …thin, …light, regular, medium, …bold, …heavy, …black medium
slant is_slant upright, italic, oblique, mathitalic, mathupright, mathshape normal
capitalization is_capitalization mixed, smallcaps mixed
serif is_serif serif, sansserif serif
spacing is_spacing proportional, mono, typewriter proportional
device is_device print, typewriter, digital, pen, artpen, chalk, marker print
category is_category ancient, attached, calligraphic, comic, decorative, distorted, gothic, handwritten, initials, medieval, miscellaneous, outline, retro, scifi, title
glyphs is_glyphs ascii, latin, greek, cyrillic, cjk, hangul, mathsymbols, mathextra, mathletters

Table 1. Kinds of font features. The notation …bold stands for all words ending with bold, such as semibold or extrabold.

The word typewriter is both a spacing and a device. All other words, except long and flat, are other features (is_other); they usually come from unusual style names (Display, Poster, …). The function remove_other removes them from a logical font (and optionally the glyph features too).

Features are normalized by normalize_feature (lower case, ultralight into thin, extended and caption into wide, nonextended into unextended), encoded for storage by encode_feature (smallcaps into SmallCaps, semibold into SemiBold, …) and decoded from user interface strings by decode_feature (Small Capitals into smallcaps, Monospaced into mono, spaces removed).

2.2.Logical fonts

A logical font is an array<string> whose first element is a family or master name and whose other elements are features. The following functions compute logical fonts for physical fonts (family, style):

string family_to_master (string f)
(master of a family)

If f is a list like cjk=SimSun,roman, it is first replaced by its main family; old names are upgraded (upgrade_family_name). If the family has features, the master is the first of them. Otherwise, the global database is loaded (see lazy loading) and the master is obtained by removing words like Mono, Console, Typewriter, Sans, Serif, Condensed, Narrow, Light, Bold, Black, … from the name (except at its very beginning). For instance, the master of an unknown family Foo Sans Mono is Foo.

array<string> master_to_families (string m)
(families of a master)

The families with master m according to font_variants, or just m if there are none.

array<string> family_features (string f)

array<string> master_features (string m)

array<string> family_strict_features (string f)
(features of families and masters)

The features of a family come from font_features (without the master) or, for unknown families, are guessed from the name (Mono, Sans, Condensed, Pen, …). The features of a master are the features which are common to all its families. The strict features of a family are its features which are not features of its master: they are the ones that distinguish a family from its siblings.

array<string> style_features (string s)
(features of a style name)

Splits a style name into words (also at lower case to upper case transitions, so that SemiBold and Semi Bold are treated alike), glues the prefixes Demi, Extra, Semi, Ultra and Small to the next word, ignores neutral words (Regular, Medium, Normal, Roman, Upright, Book, Unextended, …), translates Slanted into oblique, Inclined into italic and Versalitas into smallcaps, and normalizes the result. For instance, SemiBold Condensed Italic yields ["semibold", "condensed", "italic"].

array<string> logical_font (string family, string style)

array<string> logical_font_exact (string family, string style)
(logical descriptions of a physical font)

The first function returns the master, followed by the strict features of the family and the features of the style. The second one returns the master, followed by all features of the family, the features of the style and the glyph ranges of the characteristics (glyph_features); for CJK and Hangul fonts, the category gothic is translated into sansserif. For instance, for ("DejaVu Sans Mono", "Bold"), the first function returns ["DejaVu", "mono", "sansserif", "bold"] and the second one the same array followed by ascii, latin, greek, cyrillic, mathsymbols.

array<string> logical_font_enrich (array<string> v)
(implicit features)

Returns the master v[0] followed by the features of the master, patched (patch_font) with the features of v. This is the set of features that a request implicitly has, because they hold for all families of its master.

2.3.Translation from and to the internal naming scheme

The four argument variant of logical_font in

Graphics/Fonts/font_translate.cpp

translates an internal font description into a logical font:

  1. the family is upgraded by upgrade_family_name, which maps old TeXmacs names to database names (pagella into TeX Gyre Pagella, dejavu into DejaVu, ms-arial into Arial, modern into roman, sys-chinese into default_chinese_font_name (), etc.);

  2. the variant is split at hyphens by variant_features: ss gives sansserif, tt gives typewriter, devices, categories, glyph ranges and other words are kept, while rm is dropped;

  3. the series is kept as is (series_features);

  4. the shape is split by shape_features: right gives upright, slanted gives oblique, small-caps gives smallcaps, and stretches, italic, the math shapes, mono, proportional, long and flat are kept;

  5. the default values medium and upright are removed.

For instance, ("roman", "ss", "bold", "slanted") becomes ["roman", "sansserif", "bold", "oblique"], and ("pagella", "rm-cjk", "medium", "right") becomes ["TeX Gyre Pagella", "cjk"].

Conversely, get_family, get_variant, get_series and get_shape translate a logical font back. The family is the first element (hence a master name); the variant collects tt (for mono or typewriter), ss, devices, categories, glyph ranges and other features, joined by hyphens, with default rm; the series is the first weight, with default medium; the shape collects the stretch, the slant (right, italic, slanted, math shapes) and the capitalization (small-caps), with default right.

3.Distances between fonts

3.1.Distance between features

The function distance (string s1, string s2, bool asym) measures how badly a feature s2 of a candidate font matches a requested feature s1. Features of different kinds are at distance D_HUGE. Otherwise the distance is given by the following constants, chosen so that a mismatch of a more important kind always outweighs any number of mismatches of less important kinds:

Constant Value Situation
S_STRETCH 10 two condensed, or two wide stretches
D_STRETCH 30 other stretch mismatch
S_WEIGHT 100 two light, two bold or two black weights (bold versus semibold)
S_SLANT 100 italic versus oblique
N_WEIGHT 200 bold or black versus heavy
Q_WEIGHT 300 light versus thin, bold versus black
D_WEIGHT 1000 other weight mismatch
D_SLANT 1000 other slant mismatch
D_CAPITALIZATION 3000 capitalization mismatch
D_MASTER 10000 different master
D_SERIF 100000 serif mismatch
D_SPACING 100000 spacing mismatch (mono and typewriter are equivalent)
Q_DEVICE 300000 pen versus artpen, marker or chalk
D_DEVICE 1000000 other device mismatch
Q_CATEGORY 300000 retro versus medieval
D_CATEGORY 1000000 other category mismatch
D_GLYPHS 3000000 glyph range mismatch
D_HUGE 30000000 features of different kinds
D_INFINITY 1000000000 no candidate

Table 2. Distances between features (

Graphics/Fonts/font_select.cpp

).

Some distances are asymmetric: when asym is true, a requested bold is reasonably served by a black font (Q_WEIGHT), but a requested black is not served by a bold one (D_WEIGHT). Similarly for thin versus light, heavy versus bold and pen versus its variants.

The distance distance (string s, array<string> v, bool asym) between a feature and a logical font is zero if s is the default value of its kind and v has no feature of that kind; otherwise it is the minimum of the distances between s and the features v[1], v[2], …, bounded by the penalty for a missing feature of the kind of s (D_STRETCH, D_WEIGHT, …, D_GLYPHS, or D_HUGE for other features). As a special case, mono and proportional are at distance D_SPACING of a font with the opposite explicit feature.

3.2.Distance between logical fonts

The distance which drives the selection is

int distance (array<string> v, array<string> vx,
              array<string> w, array<string> wx);

where v is the request, vx the request enriched with its implicit features (logical_font_enrich), w the candidate as computed by logical_font (master, strict features, style features) and wx the candidate as computed by logical_font_exact (all features and glyph ranges). It is the sum of

3.3.Guessed distances

Ties are broken using the characteristics. The function characteristic_distance in

Plugins/Freetype/tt_analyze.cpp

sums: twice the discrete distances (0 or 1) for mono, sans, italic and case; relative (logarithmic) distances for ex, em, lvw, lhw, fillp, vcnt, lasprat, pasprat, loasc, lodes and dides; and three times a numeric distance for slant. A missing characteristic counts as a maximal difference.

In

Graphics/Fonts/font_guess.cpp

, guessed_distance (fam1, sty1, fam2, sty2) adds to this a category_distance between the categories of both fonts. guessed_distance_families takes the minimum over all pairs of styles (using the styles of the global database for families which are not installed), and guessed_distance (master1, master2) the minimum over all pairs of families of both masters. All three functions memoize their results.

4.Searching the closest font

4.1.search_font_among

The core loop is

void search_font_among (array<string> v, array<string> fams,
                       array<string> avoid, int& best_d1,
                       array<string>& best_result, bool strict);

It enumerates all styles (font_database_styles) of all families in fams whose master is not in avoid, and returns the best pair (family, style), or (v[0], "Unknown") if there is none. In non strict mode, the other features are removed from the request and from the candidates. Candidates are compared lexicographically by three distances:

  1. \(d_1\): the distance between logical fonts described above;

  2. \(d_2\): the plain distance between the enriched request and the exact candidate, both without other and glyph features;

  3. \(d_3\): the guessed distance between the master of the request and the master of the candidate.

The second and third distances are only computed when needed for breaking a tie.

4.2.search_font

array<string> search_font (array<string> v, bool require_exact, array<string> avoid)
(closest physical font)

Returns the pair (family, style) of the installed font which is closest to the logical font v, avoiding the masters in avoid:

  1. If v is empty, return ("TeXmacs Computer Modern", "Unknown").

  2. Let fams be the families of the master v[0]. If an exact result is required, or if v has no features besides other ones, perform a strict search among fams. The search succeeds if the distance is zero, or if an exact result was required; in the latter case, a non zero distance means that no style exactly matches, and the returned style name is built from the requested features (encode_feature).

  3. Otherwise, perform a non strict search among fams. If the distance is less than D_MASTER, refine the result by a strict search among fams.

  4. Otherwise, no family of the requested master is acceptable (typically because the font is not installed): perform a non strict search among all families of the database, take the master of the best result, and perform a strict search among the families of that master.

array<string> search_font (array<string> v, int attempt= 1)
(successive approximations)

The variant used by the rest of TeXmacs. For attempt \(= 1\), this is the previous function without exactness and without masters to avoid. For \(\operatorname{attempt}= k > 1\), the masters of the results of the attempts \(1, \ldots, k - 1\) are avoided, so that successive attempts return fonts of successively less similar masters. Results are cached in a static table. The number of attempts made by smart fonts is bounded by FONT_ATTEMPTS (20).

The function search_font_exact (v) is search_font (v, true, empty).

4.3.Substitutions

Before searching, find_closest applies the rules of

font-substitutions.scm

with apply_substitutions. A rule ((F p1 … pn) (G q1 … qm)) applies to a logical font v with v[0] equal to F if v contains all the words F, p1, …, pn; these words are removed from v and replaced by G, q1, …, qm (in front). The first applicable rule is used and the process is repeated on the result. The rules express knowledge which cannot be derived from the names, for instance that the sans serif companion of SimSun is SimHei, that the italic of STSong is STKaiti, or that CJK characters in a document typeset in roman should be taken from FandolSong (or else SimSun). Recall that a rule is only loaded if its target family is installed.

4.4.find_closest and closest_font

bool find_closest (string& family, string& variant, string& series, string& shape, int attempt= 1)
(closest available internal description)

Replaces an internal description by the closest one which can actually be constructed, and returns whether it changed. The steps are:

  1. lfn = logical_font (family, variant, series, shape), followed by apply_substitutions;

  2. pfn = search_font (lfn, attempt), a physical font (family, style);

  3. nfn = logical_font (pfn[0], pfn[1]), translated back with get_family, get_variant, get_series and get_shape;

  4. if the request asked for outline, bold, smallcaps, italic or oblique, but neither nfn nor the features guessed from the characteristics of the found font (guessed_features) have it, the suffix -poorbbb is appended to the variant, -poorbf to the series, -poorsc or -poorit to the shape. These suffixes request synthetic variants (see below).

Results are cached in a static table indexed by the original description and the attempt number.

font closest_font (string family, string variant, string series, string shape, int sz, int dpi, int attempt= 1)
(construct the closest font)

Calls find_closest and then find_font on the result. The font is registered in font::instances under the name family-variant-series-shape-sz-dpi-attempt built from the original description, so that later requests are immediate.

5.Constructing the font: find_font

5.1.From an internal description

The function find_font (family, variant, series, shape, sz, dpi) in

Graphics/Fonts/find_font.cpp

first checks font::instances for the name family-variant-series-shape-sz-dpi. Then:

  1. Synthetic variants are peeled off: a shape ending with -poorit yields poor_italic_font applied to a slightly narrowed version of the font without the suffix; -poorsc yields poor_smallcaps_font; a series ending with -poorbf yields poor_bold_font; a variant ending with -poorbbb yields poor_bbb_font (these classes are described with the smart fonts).

  2. The families sys-chinese, sys-japanese and sys-korean are replaced by the default fonts for these languages.

  3. The tuples (family variant series shape sz dpi), then (family variant series sz dpi), then (family variant sz dpi) are tried with find_font (scheme_tree).

  4. As a last resort, the TeX font (tex cmr sz dpi) is used.

5.2.From a font name

The function find_font (scheme_tree t) (through find_font_bis) recognizes the following primitive font names, which directly call the constructors listed in TeXmacs fonts:

Name Constructor
(compound …) compound_font
(truetype name sz dpi) tt_font
(unicode name sz dpi) unicode_font
(unimath up it bup bit rubber) unicode_math_font
(x name sz dpi), (qt name sz dpi) x_font, qt_font
(tex name sz dpi [dsize]), idem for cm, ec, la, gr, adobe tex_font, tex_cm_font, tex_ec_font, tex_la_font, tex_gr_font, tex_adobe_font
(tex-rubber trl name sz dpi [dsize]) tex_rubber_font
(tex-dummy-rubber font) tex_dummy_rubber_font
(error font) error_font
(math (…) (…) base error) math_font

Table 3. Primitive font names understood by find_font.

For any other head, the rewriting rules are tried. Rules are declared in Scheme with set-font-rules, which ends up in font_rule (through tm_config_rep::set_font_rules); they are stored in the table font_conversion, indexed by the head of the left hand side. A rule matches if the arities agree and all non variable atoms are equal; atoms starting with $ are variables. The first matching rule wins and its right hand side, after substitution, is looked up recursively. Here is a typical excerpt of

progs/fonts/fonts-truetype.scm

:

(set-font-rules
  ‘(((pagella $v bold italic $s $d) (unicode texgyrepagella-bolditalic $s $d))
    ((pagella $v bold $b $s $d) (unicode texgyrepagella-bold $s $d))
    ((pagella $v $a $b $s $d) (unicode texgyrepagella-regular $s $d))))

The rule files

fonts-ec.scm

,

fonts-adobe.scm

,

fonts-x.scm

,

fonts-math.scm

,

fonts-foreign.scm

,

fonts-misc.scm

,

fonts-composite.scm

and

fonts-truetype.scm

are loaded at boot time by

progs/init-texmacs.scm

.

5.3.The database fallback

If no rule exists for the head of a six element tuple (family variant series shape sz dpi), find_font_bis calls the four argument font_database_search, which computes logical_font (family, variant, series, shape), finds the closest physical font with search_font and returns its file names (font_database_search (family, style); a subfont \(n\) of a collection file.ttc is returned as file.n.ttf). The first file which exists (tt_font_exists, after removal of the extension) gives the font unicode_font (name, sz, dpi).

This is how the old and new mechanisms coexist. The families returned by find_closest are masters. For the master roman of TeXmacs Computer Modern, rules exist in

fonts-ec.scm

, so that TeX fonts are built through the rules. For a master such as TeX Gyre Pagella or DejaVu (with capitals; the rules use the old lower case names), there are no rules, and the files are found through the database. Rule heads are matched case sensitively.

6.Characters missing from the main font

A smart font first tries to render a character with its main font. If this fails, it calls smart_font_rep::resolve, which tries, for \(\operatorname{attempt}= 1, \ldots, \operatorname{FONT}\_\operatorname{ATTEMPTS}\) and for each family of the comma separated family list, a sequence of strategies (see smart fonts). The strategies related to the database are:

The second strategy is where the database does the real work. The range becomes a glyph feature of the request, for instance ["roman", "cjk"]. Since a missing glyph range costs D_GLYPHS, which is larger than D_MASTER and than all stylistic penalties, search_font prefers any font that covers the range to a font of the requested master that does not. Among the fonts that cover the range, the one with the closest features, and then the closest characteristics, is chosen. If this font still does not contain the character, the next attempt avoids its master. Substitution rules such as ((roman cjk) (FandolSong)) short-circuit the search for frequent cases.

The range hiragana (like any word which is not listed among the glyph features) is not a glyph feature, but an other feature: it does not steer the search towards suitable fonts, and only the successive attempts eventually find a font which contains the character. For Japanese and Korean, documents should rather use explicit family lists such as cjk=Name,roman (this is what sys-japanese and sys-korean expand to), in which the condition cjk also accepts hangul and hiragana characters.

When the main font has a MATH table (an OpenType or a TeX Gyre math font) and a symbol it lacks would be drawn by an emulation which a PDF export can only hold as a bitmap, the smart font takes the symbol from STIX Two Math, shipped with TeXmacs, instead of asking the database (resolve_shipped_math in

smart_font.cpp

), so that the result is the same on every system.

The default CJK fonts are determined by default_chinese_font_name, default_japanese_font_name and default_korean_font_name in

Graphics/Fonts/font.cpp

: the user preferences "default chinese font name", "default japanese font name" and "default korean font name" take precedence; otherwise a platform specific list of candidate files is checked with tt_font_exists, with roman as the final fallback.

7.Worked examples

7.1.An installed family with a style

Request ("pagella", "rm", "bold", "italic"). The logical font is ["TeX Gyre Pagella", "bold", "italic"]. Since it has two features, the first search is a non strict one among the families of the master TeX Gyre Pagella, which only contains the family of the same name. The style Bold Italic has the logical font ["TeX Gyre Pagella", "bold", "italic"] and is at distance 0; Bold is at distance D_SLANT, Italic at distance D_WEIGHT, Regular at distance D_WEIGHT plus D_SLANT. The strict refinement gives the same result. Translating back gives ("TeX Gyre Pagella", "rm", "bold", "italic") without synthetic suffixes, and find_font constructs unicode_font ("texgyrepagella-bolditalic", sz, dpi) through the database fallback.

7.2.A style provided by a sibling family

Request ("Linux Libertine", "rm", "medium", "small-caps"), that is, ["Linux Libertine", "smallcaps"]. The master Linux Libertine has the families Linux Libertine and Linux Libertine Capitals, the latter with the feature SmallCaps. Since this feature is not common to both families, it is a strict feature of Linux Libertine Capitals, so that ("Linux Libertine Capitals", "Regular") has the logical font ["Linux Libertine", "smallcaps"] and wins with distance 0, whereas ("Linux Libertine", "Regular") is at distance D_CAPITALIZATION. A genuine small capitals font is used.

7.3.A missing style

Request ("DejaVu", "rm", "medium", "small-caps"). No DejaVu family has small capitals; the best candidates, such as ("DejaVu Serif", "Book"), are at distance D_CAPITALIZATION, which is less than D_MASTER, so the master is kept (sans serif candidates additionally pay D_SERIF). Since neither the name nor the characteristics of the result provide smallcaps, find_closest returns the shape right-poorsc, and find_font builds a poor_smallcaps_font on top of DejaVu Serif.

7.4.A substitution

Request ("SimSun", "ss", "medium", "right"), that is, ["SimSun", "sansserif"]. If SimHei is installed, the substitution ((SimSun sansserif) (SimHei)) rewrites the request into ["SimHei"], which is then found exactly.

7.5.A font which is not installed

Request ("Garamond", "rm", "medium", "right") on a system without that font. The master is unknown to the local database: master_to_families prints TeXmacs] missing 'Garamond' master and loads the global database, which knows the master, the styles and the characteristics of Garamond. The strict and non strict searches among the families of the master find no installed style (distance D_INFINITY), so the non strict search is extended to all installed families. Every candidate then pays D_MASTER; among the candidates with the fewest stylistic penalties (typically the regular styles of serif, proportional, Latin fonts), the one whose master is closest to Garamond according to the guessed distance is chosen. Finally, a strict search among the families of that master selects the appropriate style.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled "GNU Free Documentation License".