GNU TeXmacsUser manualReferenceAboutEnglish
The smart font: dispatching characters to subfonts

1.Creation of smart fonts

1.1.From the environment to the font

Whenever one of the font related environment variables changes, the typesetter recomputes the current font in edit_env_rep::update_font (

Typeset/Env/env_semantics.cpp

). In text mode it calls the six argument version of smart_font with the values of font, font-family, font-series and font-shape; in mathematical mode and in program mode it calls the ten argument version, which receives both the mathematical (resp. program) font and the surrounding text font:

font edit_env_rep::make_current_font (int sz) {
  switch (mode) {
  case 2:
    return smart_font (get_string (MATH_FONT), get_string (MATH_FONT_FAMILY),
                       get_string (MATH_FONT_SERIES), get_string (MATH_FONT_SHAPE),
                       get_string (FONT), get_string (FONT_FAMILY),
                       get_string (FONT_SERIES), "mathitalic",
                       sz, (int) (magn*dpi));
  …
}

int sz= get_script_size (fn_size, index_level);
fn= make_current_font (sz);
…  // OpenType MATH: script percentages and the ssty feature
string feat= get_string (FONT_FEATURES);
if (N(feat) != 0) fn= apply_features (fn, feat);
string eff= get_string (FONT_EFFECTS);
if (N(eff) != 0) fn= apply_effects (fn, eff);

In scripts, a font with an OpenType MATH table is made again at the size given by the percentages of its table (unless math-font-sizes is set), and an untuned one is wrapped in a feature_font for its script size alternates (ssty); see mathematics from the MATH table and OpenType features.

Notice that the names of the environment variables are slightly misleading at this level: font is passed as the family argument of smart_font and font-family (rm, ss, tt, …) as the variant.

font smart_font (string family, string variant, string series, string shape, string tf, string tv, string tw, string ts, int sz, int dpi)
(math and program fonts)

If the new style fonts are disabled (the global new_fonts is false), this falls back on the rule based find_font. Otherwise the font which is actually used is the text font tf, tv, tw, ts, adapted as follows: if the text family is roman, it is replaced by the mathematical family family; the mathematical variants ms and mt select the variants ss and tt; a mathematical series other than medium replaces the text series, so that a family with a real bold math face uses it; and if the mathematical shape is right, the shape becomes the special shape mathupright. The result is the six argument smart_font applied to the adapted text font. In mathematical mode ts is mathitalic, so that the main font is the upright text font and the smart font takes care of the mathematical conventions (see below). Mathematical fonts proper are therefore usually specified inside the family list of font, using conditional entries such as math=… or mathlarge=….

font smart_font (string family, string variant, string series, string shape, int sz, int dpi)
(text fonts)

For the variant rm, this is just smart_font_bis (family, variant, series, shape, sz, dpi, dpi). For other variants, the routine first checks with logical_font and search_font whether the variant is provided by the same physical font as the rm variant. If not, it creates both smart fonts and magnifies the variant so that its x-height (yx) matches the one of the rm variant, unless the ratio is within 2.5% of one. This is why a sans serif or typewriter font taken from another family blends with the main text.

font smart_font_bis (string family, string variant, string series, string shape, int sz, int hdpi, int vdpi)
(the actual constructor)

Builds (or retrieves from the font cache) the smart font with the given horizontal and vertical resolutions. Its name has the form family-variant-series-shape-sz-vdpi-smart (with both resolutions when they differ). The routine:

  1. handles a few special cases: families starting with tc (legacy symbols of

    std-symbol.ts

    ) go directly to find_font, and the families sys-chinese, sys-japanese and sys-korean are replaced by cjk=name,roman where name is the system default (default_chinese_font_name and friends in

    Graphics/Fonts/font.cpp

    );

  2. normalizes the family list with tex_gyre_fix, kepler_fix, math_fix and profile_fix (see below);

  3. replaces the shapes mathitalic and mathshape by right for the main font;

  4. computes the main family with main_family and the base font closest_font (mfam, variant, series, sh, sz, vdpi);

  5. computes the error font error_font (closest_font ("roman", "ss", "medium", "right", sz, vdpi));

  6. constructs a smart_font_rep.

All other routines in

smart_font.cpp

which need a font with a different family, variant, series or shape call smart_font_bis again, so subfonts are often smart fonts themselves.

1.2.Family lists

The family argument of a smart font is a comma separated list. Each entry is either a plain family name or a conditional entry of the form conditions=family. Examples from the style packages in

packages/customize/fonts/

and from the code are:

mathlarge=TeX Gyre Pagella,Linux Libertine
mathlarge=TeX Gyre Pagella,cal=TeX Gyre Termes,bold-cal=TeX Gyre Termes,frak=TeX Gyre Pagella,Fira
cjk=Apple SD Gothic Neo,roman

The main family (main_family) is the first unconditional entry, or the family of the first entry if all entries are conditional. The conditions are a space separated list, all of which must hold; each condition is a |-separated list of alternatives, one of which must hold. The alternatives are tested in smart_font_rep::resolve (string c, string fam, int attempt) and may be:

If all conditions hold, family is tried for the character in the same way as an unconditional entry; otherwise the entry is skipped.

In mathematical shapes (math_fix), the condition math is removed from conditional entries, so that math=TeX Gyre Termes becomes the plain entry TeX Gyre Termes in mathematics and is ignored in text. The routines tex_gyre_fix and kepler_fix rename the short names bonum, pagella, schola, termes to the TeX Gyre families and append or remove the suffix Math according to whether a medium mathematical shape is requested, so that the dedicated OpenType math fonts are used in formulas and the text fonts elsewhere.

The last fix, profile_fix, generalizes this to the profiled OpenType math fonts (

math_font_profiles.cpp

). For each unconditional entry, in a mathematical shape a text family is replaced by the math font of its profile when that font is installed, and in a text shape a math family by its text companion; the variants ss and tt are replaced by the sans serif and typewriter companions which the profile declares, and the result is translated into its master (font_database_master), since the selection is driven by masters. A profiled font, or the text companion of one, which is installed but absent from the database is registered on the fly (register_profiled_font). See math font profiles, shipped fonts and the database.

2.The smart_font_rep class

2.1.Fields

struct smart_font_rep: font_rep {
  string mfam;        // main family
  string family;      // full family list
  string variant;
  string series;
  string shape;       // requested shape
  string rshape;      // "right" for the math shapes, otherwise shape
  int    sz;
  int    hdpi;
  int    dpi;
  int    math_kind;   // 0: no math, 1: mathitalic, 2: mathupright, 3: mathshape
  int    italic_nr;   // subfont for isolated italic letters
  bool   ot_math;     // main font: untuned OpenType math font

  array<font> fn;     // the subfonts
  smart_map   sm;     // shared character -> subfont table
  array<int> origins; // debug switch "fonts": route of each subfont
  …
};

2.2.The smart map

The smart_map is a resource whose name is the concatenation of family, variant, series and shape (get_smart_map). Since the size and resolution are not part of the key, all smart fonts which only differ by size or zoom share one smart map, and characters are resolved only once per logical font. The map stores:

fn_spec

An array of trees describing the subfonts, such as ("main"), ("error"), ("TeX Gyre Pagella" "rm" "medium" "right" "1"), ("virtual" "tradi-long") or ("poor-bold"). Entries SUBFONT_MAIN= 0 and SUBFONT_ERROR= 1 always exist.

fn_nr

The inverse table, from specification to number.

fn_rewr

For every subfont, the kind of rewriting (REWRITE_*, see below) which must be applied to strings before they are passed to it.

chv

A table of 256 integers for the one-byte (Cork) characters, with -1 for “not yet resolved”.

cht

A hash table for the universal symbols <…>, with default -1.

add_font (fn, rewr) registers a subfont specification and returns its number; add_char (fn, c) registers the font if needed and records that c is rendered by it. If a character is added twice, the smaller subfont number wins.

The actual fonts live in the array fn of each smart_font_rep. They are created on demand by smart_font_rep::initialize_font (nr) from the specification sm->fn_spec[nr]. Since the map is shared, a smart font may find in its map a subfont number for which its own fn array has no font yet; every user of a subfont number therefore checks N(fn) <= nr || is_nil (fn[nr]) and calls initialize_font first.

2.3.Construction and the mathematical shapes

The constructor installs the main font and the error font (both horizontally magnified by adjust_subfont if hdpi != dpi) and copies the mathematical parameters of the base font (copy_math_pars). For the shapes mathitalic, mathupright and mathshape it does more. The flag ot_math is set when the base font has the math type MATH_TYPE_OPENTYPE (an OpenType math font without hand-tuned tables) and its profile does not say that the letters come from the text italic (key letters):

3.Data flow when typesetting a string

3.1.Cutting a string into runs

The heart of the smart font is the routine

void smart_font_rep::advance (string s, int& pos, string& r, int& nr)
(extract the next run)

Starting at pos, scan the longest run of characters which are rendered by the same subfont. On return pos points after the run, nr is the subfont number (or -1) and r is the run, already rewritten according to sm->fn_rewr[nr].

For every character, the subfont is first looked up in chv (one byte characters) or cht (universal symbols, delimited with tm_char_forwards); if the entry is -1, the full resolution algorithm resolve (c) is run, which fills the table. A few special rules apply while building a run:

3.2.Measuring and drawing

All the public routines of the smart font are written in terms of advance:

void
smart_font_rep::draw_fixed (renderer ren, string s, SI x, SI y) {
  int i=0, n= N(s);
  while (i < n) {
    int nr;
    string r= s;
    metric ey;
    advance (s, i, r, nr);
    if (nr >= 0) {
      fn[nr]->draw_fixed (ren, r, x, y);
      if (i < n) {
        fn[nr]->get_extents (r, ey);
        x += ey->x2;
      }
    }
  }
}

get_extents combines the metrics of the successive runs: the logical widths are added, the vertical logical and ink extents are merged. get_xpositions fills the array of cursor positions; when a run was rewritten (so that the rewritten string r has a different length than the original run), the positions inside the run are set to the start of the run and only the end position is taken from the subfont. The kerning variants with an extra argument xk are implemented in the same way.

The slopes and corrections used by the mathematical typesetter are delegated to the subfont of the first run (get_left_slope, get_left_correction, get_lsub_correction, get_lsup_correction) or of the last run (get_right_slope, get_right_correction, get_rsub_correction, get_rsup_correction, get_wide_correction), and so are the height dependent script corrections get_lsub_correction_at, …, get_rsup_correction_at. The questions which concern a single glyph (get_top_accent, is_extended_shape, get_feature_variant) go to the subfont of the first character; get_rubber_variant and get_wide_variant go to the subfont which renders the numbered sizes of the character (rubber_subfont probes <name-0>), since the unnumbered name may be routed elsewhere. make_rubber_font hands the building of the extensible font to the main font when it carries a MATH table. supports always returns true: a smart font renders every character, if necessary with the error font.

When the debug switch fonts is on (DEBUG_FONTS), draw_fixed calls debug_draw instead of the subfont, which draws each run in the colour of its route (debug_origin, computed once per subfont from its specification); debug_info reports the route of one character from the routing tables, without resolving anything, for the font inspector. See inspecting the font system.

3.3.Glyph extraction and the renderers

Several clients need the actual glyph of a symbol rather than a drawing operation: virtual fonts compile their glyphs from bitmaps of the base font, emulated fonts transform bitmaps, and the renderers draw glyphs through renderer_rep::draw (int char_code, font_glyphs fn, SI x, SI y). The smart font forwards these requests to the subfont of the first run:

glyph smart_font_rep::get_glyph (string s)

int smart_font_rep::index_glyph (string s, font_metric& fnm, font_glyphs& fng)
(glyph access)

get_glyph returns the bitmap of the (first) symbol of s, index_glyph returns its index in a table of glyphs and metrics, or -1. The default implementations in font_rep print a warning (or fail if get_glyph_fatal is set), so a font which is used as the base of a virtual or emulated font must implement them.

advance_glyph moves to the next glyph boundary, taking the ligatures of the subfont into account; emulated fonts use it to draw glyph by glyph.

The drawing itself is not done by the smart font but by the leaf fonts. Note that draw_fixed draws at the font's own resolution; the public font_rep::draw (

Graphics/Fonts/font.cpp

) takes care of zooming. When the renderer has a zoom factor different from one and is not a printer, draw creates (and caches in zoomed_fn) a magnified version of the font and draws with it. For a smart font, magnify (zoomx, zoomy) returns smart_font_bis with the scaled resolutions, so that all subfonts, including virtual and emulated ones, are rebuilt at the screen resolution. Bitmap based constructions are therefore always computed at the right resolution.

4.Rewriting

Some subfonts do not use the TeXmacs encoding of the characters they render. The rewriting kind of each subfont is stored in fn_rewr, and rewrite (s, kind) is applied to each run in advance:

REWRITE_NONE

No change.

REWRITE_MATH

Characters of the form <#…> are converted into the corresponding TeXmacs names (rewrite_math, via strict_cork_to_utf8 and utf8_to_cork), for the old TeX math fonts.

REWRITE_CYRILLIC

Conversion to the T2A encoding of the TeX Cyrillic fonts (code_point_to_cyrillic_subset_in_t2a).

REWRITE_LETTERS

Unicode mathematical alphanumeric symbols are replaced by the plain letters, digits or Greek letters they are derived from (rewrite_letters, using the tables built by init_unicode_substitution); the subfont is the corresponding alphabet (bold, calligraphic, double struck, …).

REWRITE_SPECIAL

The fixed table built by is_special: - becomes <minus>, | becomes <mid>, ' becomes <#2B9>, ‘ becomes <backprime>, <hat> and <tilde> become spacing accents, the invisible symbols <noplus>, <nocomma>, …, * and the invisible big operators <big-.-1>, <big-.-2> become empty, and big operators like <big-sum-1> become the Unicode symbol <sum> when it exists.

REWRITE_EMULATE

<name> becomes <emu-name>, for the virtual font emu-bracket.

REWRITE_POOR_BBB

<bbb-X> becomes X.

REWRITE_ITALIC_GREEK

Greek letters are mapped to the mathematical italic Greek alphabet (U+1D6E2 and following, substitute_italic_greek).

REWRITE_UPRIGHT_GREEK

<upalpha> or <up-alpha> becomes <alpha> (substitute_upright_greek).

REWRITE_UPRIGHT, REWRITE_ITALIC

<up-x> and <it-x> become x (substitute_upright, substitute_italic).

REWRITE_MATH_ITALIC

Latin letters are mapped to the mathematical italic alphabet (U+1D434 and following, with U+210E for h; substitute_math_italic), for the subfont ot-italic of an OpenType math font.

REWRITE_IGNORE

The empty string. Used for characters which must not be drawn: the null delimiters such as <left-.> and <right-nobracket>, and the ideographic space <#3000> when the fonts do not provide it.

Rewriting is applied to the whole run, which is why get_xpositions has to handle runs whose rewritten length differs from the original length.

5.The kinds of subfonts

The first element of a subfont specification determines how initialize_font creates it. The following kinds exist:

main, error

The base font and the error font of the constructor.

(fam var ser sh attempt)

The generic case: closest_font (fam, var, ser, sh, sz, ndpi, attempt), where ndpi is computed by adjusted_dpi so that the x-height (characteristic ex in the font database) of the fallback font matches the one of the main family.

math, greek, cyrillic

Old style TeX fonts for the historical families, obtained through find_closest and the rule based find_font (get_math_font, get_greek_font, get_cyrillic_font).

subfont

A whole smart font for another family, used for Greek and bold letters in mathematical italic shape.

special

The same smart font in upright shape.

fast-italic, italic-math, it

The same family in italic shape.

bold-math, bold-italic-math, tt, ss, bold-ss, italic-ss, bold-italic-ss, cal, bold-cal, frak, bold-frak, bbb

Mathematical alphabets: smart fonts for the same family with variant tt, ss, calligraphic, gothic or outline and the appropriate series and shape. These are again resolved through the font database, and are emulated if the variant does not exist.

italic-roman, other

Smart fonts for shape mathitalic (for other: family roman, at an adjusted resolution), used for symbols which no Unicode font provides and which are only found in the old TeX fonts.

up, upright-greek, italic-greek, ot-italic, ignore

The main font itself, with the corresponding rewriting.

shipped-math

unicode_font ("STIXTwoMath-Regular", sz, dpi), the math font shipped with TeXmacs, for the symbols which the main font lacks and whose emulation could only be exported as a bitmap (see the resolution algorithm).

virtual

virtual_font (this, name, sz, hdpi, dpi, false): a virtual font whose base is the smart font itself (see virtual fonts).

emu-bracket

Same, for emu-bracket.

emulate

A virtual font with base the main font in extend mode, stacked on top of emu-fundamental:

font vfn= fn[SUBFONT_MAIN];
if (a[1] != "emu-fundamental")
  vfn= virtual_font (vfn, "emu-fundamental", sz, hdpi, dpi, true);
fn[nr]= virtual_font (vfn, a[1], sz, hdpi, dpi, true);
poor-bold

poor_bold_font of the medium series of the same smart font.

(poor-bbb penw penh)

poor_bbb_font of the upright smart font.

(rubber nr)

rubber_font (fn[nr]): the extensible version of another subfont (see emulated fonts).

After creation, initialize_font checks that the new subfont is not the smart font itself (same res_name), and aborts with "substitution font loop detected" otherwise.

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".