![]() |
The font selection algorithm | ![]() |
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):
in text mode, smart_font is called with the values of font, font-family, font-series and font-shape;
in math mode, the ten argument variant of smart_font is called with the values of math-font, math-font-family, math-font-series, math-font-shape, followed by the text font, family and series and the shape mathitalic;
in program mode, the ten argument variant is called with prog-font, prog-font-family, prog-font-series, prog-font-shape, followed by the text font settings, where the text variant gets the suffix -tt.
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:
if new_fonts is false, the old mechanism is used: find_font (family, variant, series, shape, sz, dpi);
families starting with tc are also handled by find_font (symbols of
std-symbol.ts
);
the families sys-chinese, sys-japanese and sys-korean are rewritten into cjk=Name,roman, where Name is the result of default_chinese_font_name (resp. the Japanese and Korean variants);
a few family name fixes are applied (tex_gyre_fix, kepler_fix, math_fix, and last profile_fix, which replaces a text family by the math font of its profile in math shapes, a math family by its text companion in text shapes, takes the sans serif and typewriter companions declared by the profile, translates the result into its master, and registers a profiled font which is installed but missing from the database; see math font profiles);
the base font is closest_font (main_family (family), variant, series, shape, sz, dpi), where main_family extracts the main family from a comma separated list like cjk=SimSun,roman, and the shapes mathitalic and mathshape are replaced by right;
the error font is derived from closest_font ("roman", "ss", "medium", "right", sz, dpi).
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.
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.
|
||||||||||||||||||||||||||||||||||||||||
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).
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):
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.
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)
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.
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)
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.
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.
The four argument variant of logical_font in
Graphics/Fonts/font_translate.cpp
translates an internal font description into a logical font:
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.);
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;
the series is kept as is (series_features);
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;
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.
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:
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
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.
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
D_MASTER if the masters differ;
the distances between each requested feature v[i] and the full candidate wx: this penalizes candidates lacking a requested property;
the distances between each distinguishing feature w[i] of the candidate and the enriched request vx: this penalizes candidates having properties which were not asked for (a Bold style when no weight was requested costs D_WEIGHT);
D_GLYPHS if the masters differ and the candidate does not cover ASCII.
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.
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:
\(d_1\): the distance between logical fonts described above;
\(d_2\): the plain distance between the enriched request and the exact candidate, both without other and glyph features;
\(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.
Returns the pair (family, style) of the installed font which is closest to the logical font v, avoiding the masters in avoid:
If v is empty, return ("TeXmacs Computer Modern", "Unknown").
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).
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.
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.
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).
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.
Replaces an internal description by the closest one which can actually be constructed, and returns whether it changed. The steps are:
lfn = logical_font (family, variant, series, shape), followed by apply_substitutions;
pfn = search_font (lfn, attempt), a physical font (family, style);
nfn = logical_font (pfn[0], pfn[1]), translated back with get_family, get_variant, get_series and get_shape;
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.
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.
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:
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).
The families sys-chinese, sys-japanese and sys-korean are replaced by the default fonts for these languages.
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).
As a last resort, the TeX font (tex cmr sz dpi) is used.
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:
|
||||||||||||||||||||||
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
.
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.
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:
At the first attempt, closest_font (fam, variant, series, shape, sz, dpi, 1) is tried for families other than the main one, for instance the SimSun of cjk=SimSun,roman, when the character belongs to the indicated range.
At attempt \(k > 1\), the Unicode range of the character is computed by get_unicode_range (in
smart_font.cpp
): ascii, latin, greek, cyrillic, cjk, hiragana, hangul, mathsymbols, mathextra, mathletters, or empty. The range is appended to the variant (rm-cjk, ss-greek, …), and closest_font (fam, v, series, shape, sz, dpi, k-1) is tried.
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.
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.
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.
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.
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.
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.