Stage 6 · Production, macros and packages 47 / 48 ≈ 27 min read

XeLaTeX, LuaLaTeX and fontspec: Unicode and System Fonts

Under XeLaTeX and LuaLaTeX a font is no longer reached through an encoding file: fontspec asks the operating system for a named OpenType face and asks that face for its features. That one change explains why inputenc disappears from a migrated preamble, why dashes and quotes work in some families and not in others, why a missing bold weight is invented instead of reported, and why Chinese text needs one further package on top of the font. This page covers the whole stack: the three family commands and the defaults that fontspec actually ships, the ligature mapping and the two good reasons to switch it off, the shape slot table and its overrides, a second script through polyglossia, babel or xeCJK, unicode-math ranges, what LuaLaTeX buys and what it costs, and an iftex-guarded preamble that still builds with pdfLaTeX.

    What you leave behind when the encoding stops being 8-bit

    Under pdflatex a font is addressed through an encoding: OT1, T1, OML and their relatives are address spaces of 256 slots, a .fd file says which slot holds which glyph in which shape, a .map file binds that description to a file on disk, and inputenc translates the bytes of a UTF-8 source into the \'e-style sequences that the slots expect. Nothing about that arrangement is wrong; it is bounded. A font can hold only what fits in the slots, a character with no slot is unreachable, and mixing two scripts in one run becomes a fight with the encoding rather than with the type designer.

    Under xelatex or lualatex, fontspec replaces all three layers at once. The encoding becomes TU, a Unicode space, so a font is named instead of numbered and a character is a code point instead of a slot. That is exactly why \usepackage[utf8]{inputenc} and \usepackage[T1]{fontenc} leave a migrated preamble: with TU there is nothing for inputenc to convert, and forcing T1 onto an OpenType font asks for an 8-bit mapping of a family being addressed by name. Keep the pair and the usual result is silent redundancy; keep fontenc with a non-TU encoding and accents get resolved by the old table instead of by the font.

    Each engine reaches fonts by its own route. XeTeX asks the platform font layer — DirectWrite on Windows, CoreText on macOS, fontconfig on Linux — for a family name, shapes the result with HarfBuzz, and adds primitives of its own: \XeTeXinputnormalization decides whether the input is normalised before lookup (NFC by default), \XeTeXlinebreaklocale hands line breaking to the platform breaker, and \XeTeXinterchartoks implements spacing rules between character classes. LuaTeX goes through luaotfload, a Lua implementation of font loading, and that is the difference which matters: a script can take part in the decision. fontspec is the single front end for both, which is why one preamble mostly serves either engine.

    The honest costs. Subsetting and OpenType shaping are not free, so a long document is measurably slower under the Unicode engines than under pdflatex, and the first LuaTeX run additionally builds a font-name database that later runs reuse. A minority of packages still assume the 8-bit world, and when a journal or thesis class says pdflatex only, believe it until you have compiled the thing twice and read the log. Decide the engine once and record it — in .latexmkrc, in CI, in the menu of the editor you use — because it is the one setting invisible in the source and fatal when two builds disagree about it.

    Engine decision tree: which job leads to pdfLaTeX, XeLaTeX or LuaLaTeX, and which font layer and packages each engine then uses STEP 1 — ASK WHAT THE DOCUMENT NEEDS, NOT WHICH ENGINE IS FASTER system OpenType or TrueType font by name · dashes and quotes from features · one non-Latin script with hyphenation Lua inside the document: callbacks on lines, boxes or fonts · reading files · computed tables · luatexja venue or class says pdfLaTeX · nothing beyond the 256-slot stack is required · shortest possible build the first two answers both leave pdfLaTeX; only the second one forces LuaLaTeX pdfLaTeX font layer: NFSS + encoding files T1/OT1 + .fd + .map + inputenc \setmainfont? no: use a font package do not add fontspec here 256 slots per encoding, so a code point outside them is unreachable. fastest on plain prose XeLaTeX font layer: fontspec, encoding TU \setmainfont · \setsansfont · \setmonofont \newfontfamily · \newfontface drop inputenc and fontenc Han text: xeCJK or the ctex classes. Silent about missing glyphs. system fonts, no Lua needed LuaLaTeX same fontspec front end, plus: \directlua{} · luacode · tex.sprint hpack_filter · post_linebreak_filter drop inputenc and fontenc too Fonts load through luaotfload, so the first run builds a name database. slowest start; pays off on callbacks \usepackage{iftex} \ifPDFTeX · \ifXeTeX · \ifLuaTeX · \iftutex — and \RequireTUTeX to refuse a wrong engine out loud Record the same decision on the build side too: $pdf_mode = 1 pdflatex · 4 lualatex · 5 xelatex in .latexmkrc, and the compiler menu of the editor.
    The decision tree from requirement to engine, and which parts of the old encoding stack each engine makes obsolete.
    % portable.tex — builds with pdflatex, xelatex *and* lualatex, unchanged.
    \documentclass[11pt,a4paper]{article}
    \usepackage{iftex}      % \ifPDFTeX \ifXeTeX \ifLuaTeX \iftutex  (+ \Require... guards)
    
    \ifPDFTeX
      % The 8-bit stack: encoding files, 256 slots, macros for non-ASCII input.
      \usepackage[T1]{fontenc}
      \usepackage[utf8]{inputenc}
      \usepackage{newtxtext,newtxmath}
    \fi
    \iftutex                % true for XeTeX *or* LuaTeX
      \usepackage{fontspec}
      \usepackage{unicode-math}
      \setmainfont{texgyretermes}[Extension=.otf, UprightFont=*-regular,
        BoldFont=*-bold, ItalicFont=*-italic, BoldItalicFont=*-bolditalic]
      \setsansfont{texgyreadventor}[Extension=.otf, UprightFont=*-regular,
        Scale=MatchLowercase]
      \setmonofont{texgyrecursor}[Extension=.otf, UprightFont=*-regular,
        Scale=MatchLowercase]
      \setmathfont{texgyretermes-math}[Extension=.otf]
    \fi
    
    % Engine-specific extras, guarded the same way.
    \iftutex
      \IfFileExists{microtype.sty}{\usepackage[activate={true,nocompatibility}]{microtype}}{}
    \fi
    \ifXeTeX
      \usepackage{xeCJK}
      \setCJKmainfont{FandolSong-Regular}[Extension=.otf, UprightFont=*,
        BoldFont=FandolSong-Bold]
    \fi
    
    % If the project may ONLY be built one way, say so in code, not in a README:
    % \RequireTUTeX        % hard stop unless XeLaTeX or LuaLaTeX
    % \RequirePDFTeX       % hard stop unless pdfLaTeX
    
    \begin{document}
    \section{Same source, three engines}
    This paragraph has a dash -- like this, an em dash --- like this,
    ``curly quotes'', and non-ASCII input: caf\'e, na\"ive, {\L\'o\'d\'z},
    $\Lambda$, plus Han input that works only where a CJK font is loaded.
    
    Under pdfLaTeX the accented runs work because fontenc and inputenc resolve them
    into slots of an 8-bit font; under the Unicode engines they work because the
    chosen font covers the code points. That difference is the entire reason a
    guarded preamble exists.
    
    \[
      \sum_{i=1}^{n} \frac{1}{i^{2}} < \frac{\pi^{2}}{6},
      \qquad
      \mathbb{E}[X] = \int_{-\infty}^{\infty} x\,f(x)\,\mathrm{d}x .
    \]
    \end{document}

    setmainfont, setsansfont, setmonofont — and the defaults fontspec ships

    Three commands cover ordinary text. \setmainfont, \setsansfont and \setmonofont fill the roman, sans and monospace family slots of the New Font Selection Scheme — internally they set \rmdefault, \sfdefault and \ttdefault — so \textsf{...}, \texttt{...} and every class default that reaches for a sans pick your faces up without further help. \setromanfont is a synonym of \setmainfont. Each takes options before and after the name, so \setmainfont[BoldFont=X-Bold]{X} and \setmainfont{X}[BoldFont=X-Bold] are the same call.

    Two further groups matter at preamble level. \defaultfontfeatures{...} sets the options applied to every family, \defaultfontfeatures+{...} appends instead of replacing, and the restricted form \defaultfontfeatures[\ttfamily]{...} applies to chosen families only. Then there are \setmathrm, \setmathsf, \setmathtt and \setboldmathrm: those do not set text families but the fonts which \mathrm, \mathsf and \mathtt use inside maths, and they are preamble-only commands, so calling one after \begin{document} is an error rather than a no-op.

    The thing people get wrong about fontspec is its defaults, because the defaults are not uniform. The shipped fontspec.cfg enables Ligatures=TeX for the roman and sans families only. The mono family gets something else: WordSpace={1,0,0}, HyphenChar=None and PunctuationSpace=WordSpace, which is why \texttt{a---b} keeps three literal hyphens, why a path in a typewriter font neither stretches at a space nor breaks at a hyphen, and why a family defined with \newfontfamily inherits neither set. Reading fontspec.cfg once turns these from surprises into rules: you add the mapping where you want it instead of assuming that the document has it.

    Sizing is the axis people fight, and it is not automatic. Scale=1.05 per family, or Scale=MatchLowercase inside a family setting, is what you want when serif and sans come from different foundries; without it the two disagree about x-height and the sans reads a point larger in every caption and table header. fontspec never applies MatchLowercase by itself — the option appears in every manual example precisely because it is something you type.

    % fonts.tex — compile with:  latexmk -pdfxe fonts.tex   (or -pdflua)
    \documentclass[11pt,a4paper]{article}
    
    % fontspec REPLACES inputenc + fontenc. Keep neither of them here.
    \usepackage{fontspec}
    \usepackage{unicode-math}
    
    % --- What fontspec.cfg already does for you:
    %     Ligatures=TeX for \rmfamily and \sffamily  (NOT for \ttfamily,
    %     NOT for families created by \newfontfamily)
    %     \ttfamily instead gets WordSpace={1,0,0}, HyphenChar=None,
    %     PunctuationSpace=WordSpace
    \defaultfontfeatures[\rmfamily,\sffamily]{Ligatures=TeX}   % explicit, idempotent
    \defaultfontfeatures+{Ligatures=TeX}                       % "+" appends, not replaces
    
    % --- The three text families. Every file named below ships with TeX Live, so the
    %     document builds anywhere without depending on the fonts of one machine.
    \setmainfont{texgyretermes}[
      Extension = .otf,
      UprightFont     = *-regular,
      BoldFont        = *-bold,
      ItalicFont      = *-italic,
      BoldItalicFont  = *-bolditalic ]
    \setsansfont{texgyreadventor}[
      Extension = .otf, UprightFont = *-regular, BoldFont = *-bold,
      ItalicFont = *-italic, BoldItalicFont = *-bolditalic,
      Scale = MatchLowercase ]        % you type this; fontspec never does it for you
    \setmonofont{texgyrecursor}[
      Extension = .otf, UprightFont = *-regular, BoldFont = *-bold,
      ItalicFont = *-italic, BoldItalicFont = *-bolditalic,
      Scale = MatchLowercase, Ligatures=TeX ]
    
    % --- Faces that are not members of a family.
    \newfontfamily\displayfont{texgyrepagella}[
      Extension = .otf, UprightFont = *-regular,
      LetterSpace = 8, Numbers = OldStyle ]
    \newfontface\ornamentfont{texgyrechorus}[
      Extension = .otf, UprightFont = *-mediumitalic ] % = \newfontfamily with the
                                                        %   shape slots left empty
    
    % --- Maths is a separate font, with separately overridable ranges.
    \setmathfont{texgyretermes-math}[Extension=.otf]
    \setmathfont{texgyrepagella-math}[Extension=.otf, range=cal]
    \setmathfont{latinmodern-math}[Extension=.otf, range={\int,\oint}]
    
    \begin{document}
    Regular \textbf{bold} \textit{italic} \textsl{slanted} \textsc{small caps};
    sans \textsf{like this}; mono \texttt{like this}.
    
    Dashes and quotes work in text: ``quoted'' -- like this --- still.
    In \texttt{monospace} they work only because of the Ligatures=TeX line above.
    
    {\displayfont A DISPLAY FACE} and oldstyle figures: 1789, 1815.
    
    \section{Maths keeps its own font}
    \[
      \oint_{\gamma} \frac{f(z)}{z-z_{0}}\,\mathrm{d}z = 2\pi i\, f(z_{0}),
      \qquad
      \mathbb{P}(A\mid B)=\frac{\mathbb{P}(A\cap B)}{\mathbb{P}(B)} .
    \]
    Uppercase Greek stays upright because unicode-math sets \texttt{math-style=TeX}
    under LaTeX, and \verb|\mathrm| pulls the *text* roman font into the formula ---
    which is what \verb|\setmathrm| in fontspec exists for.
    \end{document}

    Ligatures=TeX: what it maps, and two good reasons to turn it off

    Ligatures=TeX installs the tex-text input mapping: two hyphens become an en dash, three become an em dash, the pairs `` and '' become typographic quotes, and ~ keeps its usual meaning. It is a rule about your input convention, not a property of the font, and it is distinct from Ligatures=Common, which toggles the liga feature of the font itself (fi, fl, ff and their kin). Keeping those two apart answers half of all questions about ligatures: one changes what characters mean, the other changes how glyphs are drawn.

    The full set of ligature switches in fontspec is Required (rlig), Common (liga), Discretionary or Rare (dlig), Contextual (clig) and Historic (hlig), each with a No-prefixed counterpart, plus TeX, TeXOff and TeXReset for the input mapping. So the surgical tools are Ligatures=TeXOff to drop the dash and quote mapping for one family, Ligatures=NoCommon to keep the mapping but suppress the typographic ligatures of the font, and RawFeature=-liga when you want to address the OpenType tag directly and skip the naming of fontspec altogether.

    Why turn it off? Two real cases. First, text that must stay literal: a chemistry or linguistics document in which -- is a bond or a morpheme boundary rather than an en dash, input copied from a source that already contains en dashes and would otherwise be doubled, or code fragments in a family where three hyphens should remain three hyphens (already the behaviour of the mono family). Second, copy and paste: a ligature is one glyph standing for two letters, so searching a PDF for fi misses every word in which the font substituted it. Turning liga off for a document read on screen, or keeping it on for one that will be printed, are both defensible; what is not defensible is discovering the choice in the proof.

    Note what is not affected. \verb and verbatim environments never pass through the mapping, because they do not use a text font at all, and special characters of the input encoding are handled long before fontspec sees them. If a dash is missing inside \texttt{...} or a verbatim block, you are chasing the wrong layer — and the same goes for the reverse case, in which a typewriter font appears to honour the mapping, which means that somebody loaded \defaultfontfeatures[\ttfamily]{Ligatures=TeX} above it.

    BoldFont, ItalicFont, SmallCapsFont: the shape slot table and invented shapes

    A font request in LaTeX is a four-way lookup: family, series, shape, size. The job of fontspec is to fill the cells of that grid with file names, and every cell has an option: UprightFont, BoldFont, ItalicFont, BoldItalicFont, SlantedFont, BoldSlantedFont, SmallCapsFont, each with a matching *Features key (BoldFeatures=, ItalicFeatures=, SmallCapsFeatures=) for options that should apply to one cell only. The uses are mundane and specific: point ItalicFont at the oblique when a grotesque has no true italic; make bold in headings a different weight rather than a thickened rule with BoldFont=X-Semibold; and give SmallCapsFont an explicit file, because real small capitals are drawn rather than scaled, and a family with no smcp feature and no file will otherwise print lowercase where you asked for \textsc{...}.

    Two consequences of the cell model bite regularly. \textbf{\emph{x}} is not two effects stacked but one request — bold italic — so if that cell is empty you get whatever neighbouring file fontspec decides to stretch, which is why bold italic in a partial family looks wrong in only one of the two directions. And the grid belongs to one family: setting BoldFont= on \setmainfont says nothing about the sans or the mono, so \textsf{\textbf{...}} is still synthesised. That is not a bug; it is the structure.

    Where a cell is empty, fontspec can fill it itself. AutoFakeBold thickens the outlines and AutoFakeSlant shears the upright — both take a numeric amount, and writing the option bare means 1.5 and 0.2 respectively — while FakeStretch does the same for width, with a default of 1.2. Fake bold costs nothing at build time and shows up at display sizes and on hairline faces, where the stems close over their own counters. For body text at 10 or 12 pt it is usually invisible; for a title page it is a design decision to make on purpose rather than meet by accident.

    For a face that belongs to no family — a symbol font, a decorative single weight, one row of glyphs the main family lacks — \newfontface is the right tool, and it is defined literally as \newfontfamily with BoldFont, ItalicFont and SmallCapsFont left empty. That is worth knowing the first time a \newfontface refuses a BoldFont= option: the point of the command is that the request should never need one, and if it does, you wanted \newfontfamily. Both are used as {\myface ...}, which scopes the switch to a group and makes them safe inside a heading macro.

    The font slot grid: each LaTeX shape request resolves to one cell that fontspec fills with a file name, or invents with a fake shape ONE REQUEST = ONE CELL = ONE FILE NAME the LaTeX request cell: fam · series · shape option that fills it if the cell is empty \textrm{...} rm · md · up the font name itself — \textbf{...} rm · bx · up BoldFont = X-SemiBold AutoFakeBold (1.5) \textit{...} rm · md · it ItalicFont = X-Oblique AutoFakeSlant (0.2) \textbf{\emph{x}} rm · bx · it — one request BoldItalicFont = ... a neighbour is stretched \textsl{...} rm · md · sl SlantedFont = BoldSlantedFont AutoFakeSlant \textsc{...} rm · md · sc SmallCapsFont = X-SC smcp feature, or lowercase \textsf{\textbf{...}} sf · bx · up set on \setsansfont, not \setmainfont a second grid, per family \newfontfaceis \newfontfamily with BoldFont, ItalicFont and SmallCapsFont deliberately left empty: a face that should never be asked for a shape. Use it for a symbol or ornament file; if a bold request does arrive, you wanted the family command instead. Per-cell features exist too: BoldFeatures, ItalicFeatures, SmallCapsFeatures — the place to put Letters=SmallCaps or Numbers=OldStyle when only one cell of the grid should change. The grid is per family: main, sans and mono each own one.
    From a request to a file: the family-by-series-by-shape grid, the per-cell options that repopulate it, and the fake-shape fallback when a cell is empty.

    A second script: newfontfamily, language switching, and Han text

    Language and font are two decisions that people collapse into one. \newfontfamily\greekfont{...} followed by {\greekfont ...} changes the file that draws the characters and nothing else: not the hyphenation patterns, not the rules used to break that run, not the words LaTeX prints for \refname and dates. A language switch changes all of those. The command you want depends on which of the two is actually wrong in your document, and the honest answer is often that you wanted a font and reached for a language package, or the reverse.

    Under XeLaTeX and LuaLaTeX there are two credible routes. polyglossia was written for the Unicode engines and integrates per-language font selection with fontspec: \setdefaultlanguage{english} (a synonym of \setmainlanguage), \setotherlanguage{german}, \setotherlanguages{italian,french} for a list, then \begin{german}...\end{german} for a block or \foreignlanguage{german}{...} inline. babel grew engine-agnostic support, its own font interface \babelfont{rm}{...}, and \babelprovide for languages identified by tag rather than by module. Either is defensible; the two must never be loaded together, and if the same source has to build with pdflatex somewhere else, babel is the choice already made for you.

    Han text is not a font choice at all, which is what xeCJK is for, with luatexja as the LuaTeX counterpart. Chinese has no spaces between words, so something must decide where a line may break, how full-width punctuation is set and how much space separates Han from Latin runs; a Latin-only font loader knows nothing about any of that. \setCJKmainfont, \setCJKsansfont, \setCJKmonofont and \setCJKfamilyfont{...}{...} add a second family axis beside the Latin one and accept the same shape options as \setmainfont — with AutoFakeBold genuinely useful, since many Han faces ship in one weight — while \xeCJKsetup keys such as PunctStyle and CJKspace control punctuation and inter-script spacing, for which fontspec has no equivalent. For a document that is mostly Chinese, start from ctexart, ctexbook or ctex, which wrap that machinery in defaults and a \ctexset interface, rather than assembling it by hand.

    Coverage is what to check before trusting any multilingual source: a font is a set of code points and no engine can print a glyph absent from it. \newunicodechar{½}{\ensuremath{\tfrac{1}{2}}} maps the one or two characters you actually use onto something the current font can draw; a family chosen for its range is the structural answer; and a run which comes out blank is a coverage problem rather than a language problem, which is a different diagnosis from the one a missing font produces.

    Four independent layers of a Unicode document: the Latin family axis, the Han family axis, the language layer and the maths font, with what breaks when a layer is missing ONE STRING OF CHARACTERS, FOUR SEPARATE LOOKUPS Hello — 世界 \LaTeX{} ''quotes'' --- and a dash: Σ and Ω the input is a sequence of code points 1 · Latin text axis fontspec: \setmainfont \setsansfont \setmonofont \newfontfamily decides which file draws the run, and which OpenType features apply to it missing → the 8-bit stack answers only what fits in 256 slots of the chosen encoding 2 · Han axis xeCJK (or luatexja): \setCJKmainfont \setCJKfamilyfont \CJKfamily decides where a Han line may break, how full-width punctuation sits, the Han-to-Latin glue missing → the font loads fine and the text still breaks in the wrong place: no word spaces 3 · Language layer polyglossia: \setdefaultlanguage \setotherlanguage or babel: \babelfont \babelprovide hyphenation patterns, spellings, \refname and date words, and sometimes the font for that language missing → foreign paragraphs hyphenate by the main-language rules; both at once = error 4 · Maths font unicode-math: \setmathfont ... [range=cal] · \setmathfontface · math-style=TeX symbols, big operators, stretchy delimiters and the maths alphabets; ignores layers 1 to 3 missing → maths stays on the legacy symbol fonts, and the amssymb alphabets fight the new set Load order that works: fontspec, then the language route, then xeCJK or the ctex classes, then unicode-math — and never both language routes at once. A blank run is a coverage question for layer 1 or 2; a wrong hyphenation is a question for layer 3; a wrong glyph shape in a formula is layer 4.
    Four independent layers: the Latin family axis, the Han family axis, the language layer that drives hyphenation and shaping, and the maths font that ignores all three.
    \documentclass[11pt,a4paper]{article}
    \usepackage{fontspec}
    \usepackage{unicode-math}
    \setmainfont{texgyretermes}[Extension=.otf, UprightFont=*-regular,
      BoldFont=*-bold, ItalicFont=*-italic, BoldItalicFont=*-bolditalic]
    \setmathfont{texgyretermes-math}[Extension=.otf]
    
    % ---- Route A: polyglossia (written for the Unicode engines, pairs with fontspec)
    \usepackage{polyglossia}
    \setdefaultlanguage{english}          % \setmainlanguage is an alias of this
    \setotherlanguage{german}
    \setotherlanguages{italian,french}    % a comma list in one call
    % ---- Route B: babel (engine-agnostic: the same source still builds with pdflatex)
    % \usepackage[main=english,german]{babel}
    % \babelfont{rm}{TeX Gyre Termes}
    % \babelprovide[import]{ckb}          % languages identified by tag, not by module
    % Never load route A and route B in one document.
    
    % ---- Han, Japanese, Korean: a second axis, not a second font option.
    \usepackage{xeCJK}                     % XeLaTeX; luatexja is the LuaTeX counterpart
    \setCJKmainfont{FandolSong-Regular}[   % these four ship with TeX Live
      Extension = .otf, UprightFont = *, BoldFont = FandolSong-Bold ]
    \setCJKsansfont{FandolHei-Regular}[
      Extension = .otf, UprightFont = *, BoldFont = FandolHei-Bold ]
    \setCJKmonofont{FandolFang-Regular}[Extension = .otf, UprightFont = *,
      AutoFakeBold = 1.5 ]                  % no bold cut exists for this one
    \xeCJKsetup{ PunctStyle = CJKplain, CJKspace = true }
    % ctex route, the recommended starting point for Chinese:
    %   \documentclass{ctexart}   or   \usepackage[UTF8]{ctex}
    
    % ---- The odd character, mapped onto something the current font can draw.
    \usepackage{newunicodechar}
    \newunicodechar{½}{\ensuremath{\tfrac{1}{2}}}
    \newunicodechar{→}{\ensuremath{\rightarrow}}
    
    \begin{document}
    English text hyphenates by English rules and uses the Latin font.
    
    \begin{german}
      Ein deutscher Absatz wird nach deutschen Regeln getrennt; die Sprache
      entscheidet über Trennung, über Bezeichnungen und, wenn gesetzt, über die
      Schrift.
    \end{german}
    
    A language switch and a font switch are different tools:
    \textlatin{Latin script inside a non-Latin paragraph} is the first one,
    \emph{a foreign phrase} in the main family is only the second.
    
    汉字需要 xeCJK 这一层:中文词间没有空格,断行位置、全角标点占位、中西文之间的
    间距都要由它决定。fontspec 只负责把字体读进来,这些它管不了。
    
    Maths keeps one font whatever the surrounding language:
    \[
      \int_{0}^{1} x^{s-1} e^{-x}\,\mathrm{d}x = \Gamma(s), \qquad \Re(s) > 0 .
    \]
    \end{document}

    unicode-math: the maths font is a separate decision

    A text font has no idea how to place a limit over an integral, and an 8-bit maths font has no idea what a Unicode code point means. unicode-math hands the whole of the maths to a single OpenType maths font — Latin Modern Math, the TeX Gyre maths series, XITS, New Computer Modern Math, Fira Math — set with \setmathfont{...} after fontspec. It re-owns the symbol table and the maths alphabets, so \mathbb, \mathcal, \mathscr and \mathfrak come from that font and amssymb or amsfonts leave the preamble; packages which build on amsmath rather than redefining its symbols, mathtools above all, remain fine.

    Two defaults in the LaTeX implementation explain most reported differences. math-style=TeX is what unicode-math sets under LaTeX — the classic convention of upright uppercase Greek and italic Latin — which is why \Gamma and \mathit{\Gamma} disagree in a way that looks like a bug until you notice that the second asks for the italic cell of the maths font. And mathrm=text, mathit=text, mathbf=text, mathsf=text, mathtt=text mean that \mathrm{d}x pulls the *text* roman font into the equation, so function names and differentials match the surrounding prose: that is what \setmathrm in fontspec is for, and it is why changing \setmainfont can move your maths without a single maths command being touched. bold-style, \symup{d}, \symbf{A} and \setmathfontface complete the interface.

    When one alphabet or one symbol should come from a different font, the mechanism is a range rather than a redefinition. The named groups are up, it, bfup, bfit, sfup, sfit, tt, bb, cal, scr, frak and their bold counterparts, so \setmathfont{...}[range=cal] replaces the calligraphic alphabet alone; an explicit list works too — range={\int,\oint,\iint} to borrow only the big operators, or range={\partial,\nabla} for the two symbols which your main maths font draws badly. That is the supported route for a one-glyph fix, and it is far less fragile than a hand-written \renewcommand.

    The rest of what changes is the responsibility of the font rather than of LaTeX: extensible brackets and arrows are drawn from the maths table of the font, big operators carry their own limit placement, and the spacing around \mathrm{d} is a matter of taste to settle once in a macro. Because those properties are data in the font, a range with no coverage in the chosen file tends to produce a fallback glyph or a blank rather than an error — the same failure mode as a missing text glyph, in a place where people expect the compile to stop.

    \mathcal{A} \quad \mathscr{A} \quad \mathfrak{A} \quad \mathbb{A}
    \mathcal{A} \quad \mathscr{A} \quad \mathfrak{A} \quad \mathbb{A}
    Calligraphic, script, fraktur and blackboard bold above are four code point ranges drawn by one maths font. Under the old stack each was a separate symbol file with its own encoding, which is the whole reason amssymb stops being loaded here.
    \lim_{n \to \infty} \sum_{k=1}^{n} \frac{1}{k^{2}} = \frac{\pi^{2}}{6}
    \lim_{n \to \infty} \sum_{k=1}^{n} \frac{1}{k^{2}} = \frac{\pi^{2}}{6}

    Why choose LuaLaTeX, what it costs, and how one source survives three engines

    LuaTeX is TeX with an interpreter inside it. \directlua{...} runs Lua at the point of use; the luacode package exists mainly so that the %, # and backslash of Lua are not eaten by catcodes, which is why real code belongs inside \begin{luacode*}...\end{luacode*} rather than in a bare \directlua{}. From there the standard library is a programming environment: tex.sprint pushes tokens back into the input stream, tex.count and tex.dimen read and write registers, token builds and inspects token lists, node walks the box lists TeX is assembling, and os gives files, time and randomness.

    What that buys is work which cannot be done cleanly in macros. Line and page breaking are exposed as callbacks — pre_linebreak_filter, post_linebreak_filter, hpack_filter, pre_output_filter — so a package can see every finished line, rewrite punctuation across a line boundary, or measure every horizontal list, which means every table cell, as it is built. Font selection itself is a callback, so a script can decide which face answers a request. Generation becomes trivial: read a CSV in Lua and typeset the table, iterate until a column width settles, compute a stopping time and print it, as the last listing does with twelve rows produced by one function call.

    The costs are equally specific. LuaTeX does in Lua some of the work XeTeX does in C, and its font layer is a Lua library, so it starts more slowly and — this is what bites people — the first run after an installation or a font change builds the name database of luaotfload, a one-off cost that looks like a hang in the log. On long ordinary prose XeLaTeX is usually the faster of the two; on documents shaping several complex scripts, or which would otherwise need extra passes for a table that keeps re-measuring itself, LuaTeX can earn its interpreter back. Measure the pair on your own file with latexmk -time, which prints seconds per rule. So the choice is between capabilities rather than between speeds: take XeLaTeX for system fonts plus xeCJK and nothing further; take LuaLaTeX when a package you need is Lua-only or when line and box lists must be rewritten programmatically; stay with pdfLaTeX when the venue requires it or the build runs under a time limit.

    Whichever you choose, \usepackage{iftex} lets one file serve all three. The bundle defines \ifPDFTeX, \ifXeTeX, \ifLuaTeX and \iftutex — the last true for either Unicode engine, which is the condition you almost always want when the question is fontspec versus fontenc — and it keeps \ifpdf working with its original meaning, which is worth stating plainly because \ifpdf tests the output mode of pdfTeX, not the engine, and has produced wrong preambles for two decades. The single-purpose packages ifpdf, ifxetex, ifluatex and ifvtex are part of the same bundle today, so one line covers all of them. A guard then costs one line each: \ifPDFTeX ... \fi around fontenc, inputenc and a Times clone; \iftutex around fontspec, unicode-math and the family commands; \ifXeTeX around xeCJK, since luatexja is the counterpart.

    A file can also refuse a wrong engine out loud, which beats failing obscurely: \RequireTUTeX, \RequireXeTeX, \RequireLuaTeX and \RequirePDFTeX stop the run with a named requirement, so put the requirement in the document rather than only in a README — the README is not read by the person whose build broke. The build-side half of the same decision belongs to the next lesson ($pdf_mode = 5 for XeLaTeX, 4 for LuaLaTeX in .latexmkrc), and it is one choice recorded twice. What a portable preamble does not fix: classes which assume one encoding, maths whose output shifts because two maths packages disagree about a symbol, and differences in colour or hyphenation visible only in the proof. Portability means the file compiles everywhere; it does not mean the result is identical everywhere, and where it must be, pick one engine and pin it.

    % lua.tex — compile with:  latexmk -pdflua lua.tex
    \documentclass[11pt,a4paper]{article}
    \usepackage{fontspec}
    \usepackage{unicode-math}
    \usepackage{booktabs}
    \usepackage{luacode}   % safe catcodes for Lua blocks; a bare \directlua lacks them
    \setmainfont{texgyretermes}[Extension=.otf, UprightFont=*-regular,
      BoldFont=*-bold, ItalicFont=*-italic, BoldItalicFont=*-bolditalic]
    \setmathfont{texgyretermes-math}[Extension=.otf]
    
    \begin{luacode*}
      -- Data, formatting decisions and iteration live in Lua, not in nine \loop macros.
      function collatz_table (first, count)
        local rows = {}
        for i = first, first + count - 1 do
          local m, steps = i, 0
          while m > 1 do
            if m % 2 == 0 then m = m // 2 else m = 3 * m + 1 end
            steps = steps + 1
          end
          rows[#rows + 1] = string.format("%d & %d \\\\", i, steps)
        end
        tex.sprint(table.concat(rows, "\n"))
      end
    \end{luacode*}
    
    \begin{document}
    \section{Typesetting driven by computation}
    
    \begin{center}
    \begin{tabular}{rr}
    \toprule
    $i$ & stopping time \\
    \midrule
    \directlua{collatz_table(27, 12)}
    \bottomrule
    \end{tabular}
    \end{center}
    
    The same hook reaches the line-breaking machinery: \texttt{pre\_linebreak\_filter}
    and \texttt{post\_linebreak\_filter} see the list of lines before and after a
    break is chosen, \texttt{hpack\_filter} sees every horizontal list (so every
    table cell) as it is built, and \texttt{define\_font} lets a script decide which
    font answers a request. That is why packages which rewrite punctuation across a
    line boundary, hyphenate two scripts at once, or colour individual glyphs are
    usually written for LuaTeX first.
    
    The trade is real: font loading in LuaTeX is a Lua library, so the first run
    after an install or a font change builds a name database, and the per-page work
    runs inside an interpreter. Measure it on your own document with
    \texttt{latexmk -time}.
    
    \[
      \sum_{k=1}^{n} \frac{1}{k^{2}} \to \frac{\pi^{2}}{6},
      \qquad
      \int_{0}^{\infty} e^{-x^{2}}\,\mathrm{d}x = \frac{\sqrt{\pi}}{2} .
    \]
    \end{document}

    When the font is missing, substituted, or the wrong one

    fontspec defers the lookup: the family name is resolved when a character first needs the font, not when \setmainfont is read. The failure therefore appears later than the cause, often mid-paragraph and in another file, as Requested font "Cambria/OT" ... not found or as a fontspec error naming the family. Search the log for the font name instead of following the line number above it, and expect the fix to be the name string more often than the installation.

    A name which misses is checked in one command: fc-list | grep -i cambria and fc-match "Segoe UI" on Linux, the Fonts panel of the Settings app on Windows (the family column, not the file name), the Info window of Font Book on macOS. Two traps deserve internalising. fontconfig substitutes silently when a name misses, so the build succeeds, the PDF looks plausible, and pdffonts out.pdf is the only thing which tells you which face you actually got. And lookup by file rather than by name needs the parts the operating system would have inferred: Path=, Extension= and one option per cell of the shape grid, with * standing for the base name — UprightFont=*-regular — which is also how you stop a build depending on the fonts of whichever machine ran it last.

    An absent glyph behaves differently by engine. LuaTeX is explicit: Missing character: There is no X in font ... for every occurrence, so one grep of the log lists every unsupported code point in the document. XeTeX is quiet: it draws nothing and prints nothing, and you meet the problem in the proof. A character which is present but wrong is nearly always one of three causes — normalisation, since an e plus a combining acute and a precomposed é are two different requests and \XeTeXinputnormalization decides which one your file contains; shaping, since a wrong Script or Language gives glyph variants you did not ask for; or substitution, which pdffonts shows at once.

    The diagnostic pass which answers all of it takes a minute and is worth doing in order: \listfiles at the top of the preamble so the log records every file and version used, pdffonts on the output for what was embedded and subset, fc-list and fc-match for what the system thinks a name means, and a timing pair around any region you suspect of being slow. Only then change something, because the commonest cause of a font problem which resists three fixes is a diagnosis that was guessed at rather than read.

    \sqrt[3]{\left\lvert \frac{z_{1}}{z_{2}} \right\rvert} = \frac{\lvert z_{1}\rvert^{1/3}}{\lvert z_{2}\rvert^{1/3}}
    \sqrt[3]{\left\lvert \frac{z_{1}}{z_{2}} \right\rvert} = \frac{\lvert z_{1}\rvert^{1/3}}{\lvert z_{2}\rvert^{1/3}}
    The radical and the vertical bars above are drawn by the maths font at whatever height the formula needs. That extensibility is data inside the font, and it is the clearest visible difference between a Unicode maths font and the 8-bit assemblies it replaces.

    Lesson cheat sheet

    One key line of code from each section — jump to it or copy it straight from here.

    Section Key code
    \documentclass[11pt,a4paper]{article}
    \mathcal{A} \quad \mathscr{A} \quad \mathfrak{A} \quad \mathbb{A}
    \sqrt[3]{\left\lvert \frac{z_{1}}{z_{2}} \right\rvert} = \frac{\lvert z_{1}\rvert^{1/3}}{\lvert z_{2}\rvert^{1/3}}

    Common mistakes

    • Keeping \usepackage[utf8]{inputenc} and \usepackage[T1]{fontenc} after moving to xelatex. fontspec replaces that stack; the pair is at best inert and at best forces an 8-bit encoding onto a font being addressed by name.
    • Assuming Ligatures=TeX is on everywhere. The shipped fontspec.cfg enables it for the roman and sans families only, so \texttt{a---b} and any family made with \newfontfamily keep literal hyphens until you ask.
    • Naming a font by its file stem or by the marketing name on the vendor page instead of the family name reported by the operating system. Verify with fc-match, or stop depending on installed fonts: Path=, Extension= and one option per shape.
    • Setting BoldFont= on \setmainfont and wondering why bold sans is still synthesised. Each of main, sans and mono has its own shape table, and \textbf{\emph{x}} asks for a bold italic cell which may be empty.
    • Loading amssymb or amsfonts next to unicode-math: both own the double-struck and fraktur commands, so the result is a redefinition warning or a silently wrong alphabet. Use range= to take one alphabet from another maths font instead.
    • Expecting an error for a missing glyph under XeLaTeX. It prints nothing and draws nothing; grep Missing character under LuaLaTeX, or check the coverage of the font before trusting a multilingual run.
    • Loading polyglossia and babel in one document. Pick a route; if the source must also build with pdflatex, the choice has already been made for you.
    • Trying to solve Han line breaking with a larger Latin font. fontspec can load a Han face perfectly and still break the line in the wrong place: xeCJK, or luatexja, supplies the breaking, punctuation and inter-script spacing layer.
    • Reaching for AutoFakeBold on display headings because the family has no bold. It is free at build time and visibly wrong at 20 pt; buy the real semibold file for anything large.

    Questions about this lesson

    Do I need fontspec when I use XeLaTeX or LuaLaTeX?
    You need it for any font that lives in the operating system, which is the usual reason to switch engines at all. Without it the Unicode engines still load classic TeX fonts through .fd and .map files and you keep the old limits; with it, \setmainfont, \setsansfont and \setmonofont replace inputenc, fontenc and the family packages in one step and expose OpenType features by name. If you stay on pdfLaTeX and want a text face such as Times, the equivalent is a font package (newtxtext with newtxmath, say), because fontspec cannot work there.
    What does Ligatures=TeX do, and why are my dashes broken?
    It installs the tex-text input mapping that turns -- and --- into en and em dashes and the pairs of back and forward apostrophes into typographic quotes. fontspec enables it for the main and sans families through fontspec.cfg, but not for the mono family and not for families created by \newfontfamily — so broken dashes are usually a question of which family you are in, not of whether fontspec is loaded. Add \defaultfontfeatures[\ttfamily]{Ligatures=TeX} or pass the option to the single font. Ligatures=TeXOff does the reverse for input in which the hyphens must stay literal.
    How do I use a font that is not installed on the system?
    Point fontspec at files instead of at a family name: \setmainfont{myfont}[Path=./fonts/, Extension=.otf, UprightFont=*-regular, BoldFont=*-bold, ItalicFont=*-italic, BoldItalicFont=*-bolditalic]. The asterisk stands for the base name, a bracketed name such as {[myfont]} forces file lookup, and each shape gets its own cell. This is also how you make a build reproducible, because the result stops depending on which fonts the machine happens to have.
    Should I use XeLaTeX or LuaLaTeX?
    Choose by capability rather than by speed. Both read system OpenType fonts through fontspec and both need unicode-math for maths. LuaLaTeX additionally runs Lua inside TeX, so it can rewrite line breaking and box lists through callbacks, read files, compute table content and drive packages such as luatexja; the price is a slower start and a first-run font database built by luaotfload. If all you need is system fonts plus a second script, XeLaTeX is the smaller change. Whichever you pick, record it in .latexmkrc and in CI, because a source that compiles with either still produces different output with each.
    How do I typeset Chinese, Japanese or Korean with XeLaTeX?
    With a layer on top of fontspec rather than with fontspec alone. Load xeCJK and use \setCJKmainfont, \setCJKsansfont, \setCJKmonofont and \setCJKfamilyfont; that adds a second family axis and, more importantly, the line breaking, full-width punctuation and Han-to-Latin spacing that a Latin font loader knows nothing about. For a mainly Chinese document start from the ctex classes (ctexart, ctexbook, ctexbeamer) or \usepackage[UTF8]{ctex}, which configure xeCJK with sensible defaults. The LuaTeX counterpart is luatexja.
    Does unicode-math replace amssymb and amsfonts?
    For the maths alphabets and most of the symbol table, yes: one maths font supplies double-struck, calligraphic, script and fraktur, so amsfonts and amssymb leave the preamble, and you stop assembling delimiters and arrows by hand. Coverage then follows the chosen font rather than the package, so check the symbols you lean on. The supported way to borrow a subset is \setmathfont{other font}[range={\int,\oint}] or range=cal for a whole alphabet, not a \renewcommand of each command.

    Live playground: edit the LaTeX, see it render

    The preview updates as you type — break it on purpose to see how errors look.

    KaTeX error
    Try an example

    Keep reading

    Three ways into the same idea: the notation itself, the lesson that teaches it, and an article that applies it.