GNU TeXmacsUser manualReferenceAboutEnglish
The font database: files, lifecycle and characteristics

1.The tables of the database

The font database consists of a few global hash tables, all defined in

Graphics/Fonts/font_database.cpp

. Keys and values are Scheme trees (tree objects whose leaves are strings), which makes it trivial to load and save them as Scheme files.

hashmap<tree,tree> font_table

Associates to each physical font, given as a pair (family style), the list of its known locations. A location is a triple (file index size) of strings: the base name of the font file (without directory), the index of the subfont inside a .ttc collection (0 for ordinary files) and the size of the file in bytes. Several locations can be registered for the same font, for instance when different versions of a file exist on different systems; the size is used to distinguish them.

hashmap<tree,tree> font_global_table

The same kind of table for the global database. It is only loaded on demand (see below) and is only used in order to know which styles exist for a family that is not installed locally.

hashmap<tree,tree> font_features

Associates to each family name a tuple whose first element is the master family and whose other elements are features, such as SansSerif, Mono, Calligraphic or Handwritten. A master groups several families which belong to the same design: for instance DejaVu Sans, DejaVu Sans Mono and DejaVu Serif all have the master DejaVu.

hashmap<tree,tree> font_variants

The inverse of the previous table: it associates to each master the tuple of its families. It is not stored on disk, but recomputed by font_database_load_features.

hashmap<tree,tree> font_characteristics

Associates to each physical font (family style) the tuple of its automatically computed characteristics (see below).

hashmap<string,tree> font_substitutions

Associates to a family name a tuple of substitution rules (see the selection algorithm).

In addition, the global boolean new_fonts (accessed through set_new_fonts and get_new_fonts) records whether the database based selection is enabled at all. It mirrors the user preference "new style fonts".

2.The files of the database

2.1.File format

All database files are sequences of Scheme expressions, one per line, read with block_to_scheme_tree and written with scheme_tree_to_block. Spaces inside names are escaped by a backslash. When saving, the entries are sorted case insensitively (font_less_eq_operator), which keeps the files readable and makes their differences meaningful under version control. Here are typical entries of the four main files:

;; font-database.scm: (family style) -> locations
((TeX\ Gyre\ Pagella Bold) ((texgyrepagella-bold.otf 0 219564)))
((Al\ Nile Bold) ((Al\ Nile.ttc 1 124996) (Al\ Nile.ttc 2 131264)))
((TeXmacs\ Computer\ Modern Bold) ((ecbx10.tfm 0 3200)))

;; font-features.scm: family master feature …
(DejaVu\ Sans DejaVu SansSerif)
(DejaVu\ Sans\ Mono DejaVu Mono SansSerif)
(TeXmacs\ Computer\ Modern\ Sans roman SansSerif)

;; font-characteristics.scm: (family style) -> characteristics
((TeX\ Gyre\ Pagella Regular) (Ascii Latin Greek mono=no sans=no slant=0 italic=no case=mixed regular=yes ex=79 em=200 lvw=20 lhw=8 …))

;; font-substitutions.scm: (family property …) (family property …)
((SimSun sansserif) (SimHei))
((roman cjk) (FandolSong))

Notice that TeX fonts also appear in the database: the family TeXmacs Computer Modern (master roman) is located in .tfm files. Features are written in “camel case” (encode_feature) and normalized to lower case when read (normalize_feature); substitution files directly use the lower case forms.

2.2.Global and local files

The following files are involved (macros at the top of

font_database.cpp

):

$TEXMACS_PATH/fonts/font-database.scm,
font-features.scm
,
font-characteristics.scm

The global database, shipped with TeXmacs (in the source tree:

src/TeXmacs/fonts

). It describes several thousands of fonts which are commonly found on Linux, macOS and Windows systems or in TeX distributions (more than a thousand families), whether or not they are installed on the current machine. The features are curated by hand.

$TEXMACS_PATH/fonts/font-substitutions.scm

Substitution rules; there is no local version of this file.

$TEXMACS_PATH/fonts/font-features.bis.scm

Output file of font_database_build_global for the features (see below); it is never read.

$TEXMACS_HOME_PATH/fonts/font-database.scm,
font-features.scm
,
font-characteristics.scm

The local database: the fonts which are actually available for the user. This is the database that is used for all queries.

$TEXMACS_HOME_PATH/fonts/delta-database.scm, delta-features.scm, delta-characteristics.scm

The entries of the local database which are not in the global one, written by font_database_save_local_delta. They are used by maintainers in order to inspect new fonts before adding them to the global database.

$TEXMACS_HOME_PATH/fonts/shipped-stamp.scm

Two lines written by font_database_load whenever it merges the global database into the local one: the dates and sizes of the three global files followed by the value of TEXMACS_PATH (shipped_fonts_stamp), and the number of entries of the local database after the merge (see loading below).

The file $TEXMACS_PATH/fonts/pdf-font-issues.scm is unrelated to the database proper: it lists font files that need a special treatment by the PDF renderer (no_font_issues in

Plugins/Pdf/pdf_hummus_renderer.cpp

).

3.Lifecycle of the database

3.1.Loading

All query functions start by calling font_database_load, which does nothing after the first successful call (flag fonts_loaded). Otherwise, it proceeds as follows:

  1. Decide whether the shipped database has to be merged into the local one. This is the case when the first line of shipped-stamp.scm differs from the current stamp (the global files changed, typically after an upgrade which registers new fonts, or another installation uses the same home directory), or when the stamp is missing (shipped_fonts_changed), and also when the local database has fewer entries than the second line of the stamp records, because another installation rebuilt it without the fonts that this one ships (shipped_fonts_shrunk).

  2. Load the local database into font_table. If it is empty or missing (first start, or after an upgrade or a cache clearance), or if a merge is due, load the global database (whose entries are added to the local ones, replacing those with the same key), keep only those entries whose files exist in the font path of this machine (font_database_filter), and save the result as the local database.

  3. Similarly load the local features. If there are none, or if a merge is due, load the global features, keep only those of the families present in font_table (font_database_filter_features) and save them locally. While loading features, font_variants is rebuilt.

  4. Similarly for the characteristics (font_database_filter_characteristics).

  5. Load the global substitutions (font_database_load_substitutions). A rule is only retained if its target family has at least one style in font_table, so that substitutions never lead to missing fonts.

  6. After a merge, write the new stamp and the number of entries to shipped-stamp.scm.

Without the merge, a font that a new version of TeXmacs registers in its global database, such as the OpenType math fonts it now ships, would stay invisible to a home directory written by an older version, and the characters which only that font draws would come out as their names in red.

In other words, on first start the local database is the intersection of the global database with the files on disk. Apart from the sizes of the files, which are used to identify them, font files are not analyzed at this stage. Fonts that are installed but unknown to the global database are only discovered by an explicit scan (see below), with one exception: a profiled OpenType math font which is installed but not in the database (the math fonts of a TeX distribution are the usual case) is added to the local database the first time a document asks for it, by register_profiled_font in

smart_font.cpp

, which calls font_database_extend_local on the file named by the profile (and on the directory of its text-file). As a side effect, that directory is added to the preference "imported fonts"; see math font profiles.

3.2.Filtering the global database

font_database_filter works with two temporary tables. The table back_font_table, built by build_back_table, maps each location (file index size), and also each pair (file index), to the keys (family style) which use it. Then font_database_collect traverses the font directories (tt_font_path and tfm_font_path). For each .ttf, .ttc, .otf or .tfm file and each subfont index \(j = 0, 1, ...\), it looks up the location (file j size):

3.3.Lazy loading of the global database

When the selection code meets a family or a master which is unknown to the local features (functions family_to_master and master_to_families, with an exception for the pseudo families tc and tcx), it prints TeXmacs] missing 'name' family (resp. master), once per name (report_once), and calls font_database_global_load, which itself prints TeXmacs] warning, missing font, loading global substitution list. This function, executed at most once (flag fonts_global_loaded), loads the global database into font_global_table, and merges the global features and characteristics into font_features and font_characteristics. Consequently, the selection algorithm knows the master, the features, the styles (font_database_global_styles) and the characteristics of fonts which are used by a document but which are not installed, and it can use this knowledge in order to find a similar installed font. The table font_table itself is not modified, so that an uninstalled font is never selected.

3.4.Scanning the disk

The function font_database_build adds the fonts found at a given url to font_table. It recurses through URL disjunctions and directories; in directories, only files with extensions .ttf, .ttc and .otf are considered (a single file given explicitly is processed whatever its extension). Files on a small blacklist (on_blacklist) are skipped, and so are the files whose name and size are already recorded in font_table: the index scanned_files of such pairs is built from the table by font_database_init_scanned before each scan. For each new file, it calls tt_font_name to obtain one pair (family style) per subfont, and registers the location (file index size) for this pair. Since tt_font_name drops Medium from the family names, a medium face may be filed under the same style as the regular one, and the first location of a pair is the one used: medium_last therefore puts the files whose name contains Medium after the others, after each insertion and also when a database file is loaded (font_database_load_database). The names of the processed files are only printed in verbose debug mode, and a scan ends with a count of the new and skipped files.

The scanning functions available to the rest of TeXmacs are:

void font_database_build_local ()
(full scan of the font path)

Loads the database, scans tt_font_path (), computes the missing characteristics (font_database_build_characteristics (false)), guesses features for the families that have none (font_database_guess_features) and saves the local database. This is the implementation of Tools\(\rightarrow\)Fonts\(\rightarrow\)Scan disk for fonts (scan-disk-for-fonts). Since known files are skipped and the characteristics are only computed for styles which have none, a rescan of a complete database takes seconds; the first scan of a system with many fonts may still take minutes, since every new font is rendered for its analysis.

void font_database_extend_local (url u)
(import fonts)

Adds the directory of u (or u itself if it is a directory) to the preference "imported fonts" (tt_extend_font_path), so that it becomes part of the font path in future sessions, and then does the same as the previous function, but only for u. This is called by the Import button of the font selector.

void font_database_build_global (url u)
(extend the global database)

For maintainers: reloads the global database, scans u, computes the characteristics and guessed features of the new fonts, and writes

font-database.scm

and

font-characteristics.scm

in $TEXMACS_PATH/fonts. The features are written to font-features.bis.scm instead of

font-features.scm

, so that the guessed features can be reviewed and merged by hand. The variant without argument scans the whole tt_font_path (). In Scheme these are font-database-insert-global and font-database-build-global. Since the function changes the in-memory tables, TeXmacs should be restarted afterwards.

void font_database_save_local_delta ()
(save the difference between the local and global databases)

Writes the entries of the local database whose keys are not in the global one to the delta-*.scm files and resets all tables (they are reloaded at the next query). The families of the delta are returned by font_database_delta_families.

3.5.The font path

The directories which are scanned, and in which font files are looked up, are given by tt_font_path in

Plugins/Freetype/tt_file.cpp

. This is a disjunction of the following directories, each of them searched recursively (search_sub_dirs):

On macOS, the TeX Live directories are found whatever their year: texlive_font_dirs lists the installations under /usr/local/texlive, /usr/share/texlive, /opt/texlive and $HOME/texlive. On the other Unix systems the list still names TeX Live 2020 to 2022 only (

tt_file.cpp

, tt_font_path), so that fonts in other places (for instance $HOME/.local/share/fonts, or a more recent TeX Live) are only found after an explicit import or through TEXMACS_FONT_PATH.

4.Reading font files

4.1.Locating a font file

Throughout the font code, a font file is designated by its base name without extension, such as texgyrepagella-bold or DejaVuSans. The function tt_font_find maps such a name to a url, using the persistent cache font_cache.scm (key "sfnt:" followed by the name; the prefix was changed from "ttf:" when the order below changed, so that answers cached by an older version are not reused). On a cache miss, tt_font_find_sub successively tries:

  1. tt_unpack: if the name ends with an integer suffix, as in Al Nile.1, the subfont 1 of the collection Al Nile.ttc is extracted (tt_extract_subfont) into $TEXMACS_HOME_PATH/fonts/unpacked/Al Nile.1.ttf, which is returned. This is how fonts in .ttc collections are made accessible to the rest of TeXmacs.

  2. the extensions .otf, .ttf, .ttc, .pfb and .dfont, in this order, using tt_locate. The sfnt formats come before Type 1: a TeX distribution ships many families in both forms, and the .pfb file carries a TeX encoding instead of a Unicode character map, besides having no OpenType layout tables; .pfb files are searched in the TeX distribution (resolve_tex), the others in tt_font_path (and optionally with the system locate command, when the global flag use_locate is set, which is currently never the case).

The predicate tt_font_exists additionally caches its answers in memory. The function tt_find_name looks for design size variants of a font (such as ecrm10 or ecrm12); it is mostly relevant for TeX fonts.

4.2.Parsing TrueType and OpenType files

The file

Plugins/Freetype/tt_tools.cpp

reads font files directly, without FreeType. A file is loaded into a string and accessed with big endian readers (get_U16, get_U32, get_tag). The main routines are:

scheme_tree tt_font_name (url u)
(family and style names of the fonts in a file)

Returns a tuple with one pair (family style) per subfont of u, or an empty tuple if the file cannot be read or if one of its subfonts has an unsupported version. The names are normalized: words describing a stretch or a weight which some vendors put into the family name (Narrow, Condensed, Light, Semibold, Bold, Black, Italic, etc.) are moved to the style by move_to_shape (with spelling normalizations, such as Ultralight into Thin, and Medium simply dropped); leading non alphabetic characters are removed; all capital family names are converted to lower case; the first letter is capitalized; and STIX becomes Stix. Exported to Scheme as tt-font-name.

void tt_dump (url u)
(print the contents of a font file)

Prints the list of tables, the family and style names, and all records of the name table for each subfont. Useful in order to understand why a font gets a strange name in the database. Exported to Scheme as tt-dump.

The same file contains the readers of the OpenType layout tables MATH, GSUB and GPOS, which are not used by the database but by the fonts themselves, through the parsed tables that

tt_face.cpp

keeps per face; they are described in the OpenType layout tables.

5.Font characteristics

5.1.Computation

The characteristics of a font are computed by font_database_build_characteristics, which, for every key of font_table without characteristics (or for all keys, if force is true), derives a font name from its locations (file.ttc with index \(n\) becomes file.n, the extension is removed, and a trailing 10 is removed for .tfm files if needed) and calls tt_analyze on it.

array<string> tt_analyze (string family)
(compute the characteristics of a font)

Loads the font with tt_font and tt_font_metric at 10pt and 1200dpi, temporarily disables fatal errors for missing glyphs (get_glyph_fatal), and calls analyze_range, analyze_special and analyze_major in

Plugins/Freetype/tt_analyze.cpp

. Without FreeType support, it returns an empty array. Exported to Scheme as tt-analyze.

The characteristics are of two kinds: glyph ranges (plain words) and attributes of the form name=value.

Glyph ranges (analyze_range)

Ascii and Latin if all characters in 0x21-0x7e, respectively 0xc0-0xff, have a non empty bounding box; Greek and Cyrillic if more than two thirds of the basic letters are present; CJK, Hangul, MathSymbols (0x2000-0x23ff), MathExtra (0x2900-0x2e7f) and MathLetters (0x1d400-0x1d7ff) if more than 20% of the corresponding range is present. TeX ec*10 fonts are declared to support the first four ranges. Greek and Cyrillic are removed again by sane_font if a test letter is missing, or, in CJK fonts, if it looks like a full width glyph.

Special properties (analyze_special)

mono=yes if all letters have the same advance width; sans=yes if the glyph L has no serifs (is_sans_serif); slant=n, the slant of [ times 100; italic=yes if the a has the italic (single storey) form and the f descends below the baseline; case=mixed, caps or smallcaps depending on the heights of lower case letters compared to upper case ones; regular=yes if the x-height letters have a regular height.

Metric properties (analyze_major)

ex (the x-height, an absolute value at the fixed size of the analysis), and, relative to it (in percent): em (width of M), lvw and lhw (vertical and horizontal stroke widths of o), uvw and uhw (the same for O), lasprat and pasprat (average logical and ink widths of lower case letters), loasc and lodes (maximal ascent and descent of lower case letters) and dides (descent of digits). Finally fillp is the average fill rate of the letters and vcnt the number of black pixels per unit of width: both measure the weight.

A few accessors return metric characteristics as ratios with respect to the x-height (get_M_width, get_lo_pen_width, get_up_pen_width, …); they are used by the font emulation code (for instance for synthetic blackboard bold). The function analyze_trace, which computes “traces” of glyph widths and heights, is currently disabled.

5.2.Features guessed from characteristics

The function guessed_features (family, style) in

Graphics/Fonts/font_guess.cpp

translates characteristics back into features:

The variant guessed_features (family, pure_guess) computes the features of a whole family: the features guessed for each style are merged into the features obtained from the names (cautious_patch, which never overrides a feature of the same kind), and only the features common to all styles are kept, except those which vary between styles according to the names. The result starts with the master (family_to_master). This is how font_database_guess_features provides features for newly scanned families; since family_to_master strips words like Sans, Mono or Condensed from unknown family names, the families Foo Sans and Foo Serif automatically get the same master Foo.

6.Caches and their invalidation

Besides the local database itself, the following caches are involved:

$TEXMACS_HOME_PATH/system/cache/font_cache.scm

The persistent cache of tt_font_find and tt_find_name (

System/Misc/data_cache.cpp

). Positive entries are checked for existence and discarded if the file disappeared; negative entries (font not found) are trusted.

$TEXMACS_HOME_PATH/fonts/unpacked/

Subfonts extracted from collections. They are never refreshed automatically.

$TEXMACS_HOME_PATH/fonts/error/

Markers for TeX fonts which could not be generated (

Plugins/Metafont/load_tex.cpp

). They are removed at startup by cache_initialize when the

fonts/type1

or

fonts/truetype

directories of $TEXMACS_PATH or $TEXMACS_HOME_PATH changed.

In memory

The answers of tt_font_exists; the caches of search_font and find_closest; the memo tables of the guessed_distance functions; and the table font::instances of all constructed fonts, indexed by name.

These caches are invalidated in the following situations:

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