十个在 TeX 眼里先于你有意义的字符
TeX 不是把你的文件当文本读。它的输入处理器把每个字符归进一个类别——转义、开组、闭组、数学切换、对齐列分隔、行末、参数、上标、下标、活动字符、注释、字母、其它、非法——而只有其它和字母两类会作为字形抵达页面。有十个字符开箱即不是其它,这就是它们需要处理的全部原因:\ 是转义,{ 与 } 分组,$ 切换到数学,& 是对齐列分隔符,# 标记宏参数,^ 与 _ 是上标与下标字符,~ 是活动字符(LaTeX 把它赋成不断行空格),% 开始一条注释。
转义规则只有一行:反斜杠后跟一个非字母,就构成一个长度为二的控制序列,意思是「那个字符,原样」。所以 \%、\$、\&、\#、\_、\{、\} 就是 \ 加上字符本身,它们能用是因为这些名字在内核里都有定义。三个没有这种捷径的字符,恰好是转义写法会自我指涉或有歧义的:反斜杠本身是 \textbackslash,波浪号是 \textasciitilde,抑扬号是 \textasciicircum,出于对称,反重音号是 \textasciigrave。
人们以为是特殊字符、其实不是的那些:<、>、|、"、?、/、* 在朴素 LaTeX 里都属于其它类,因此原样排出。两个警告。< 与 > 这两个字形在更老的 OT1 字体编码里不存在,于是可能静默地什么都不印——T1 里有,而 \textless/\textgreater(来自 textcomp)是不依赖编码的答案。另外 " 会被某些 babel 语言选项激活(德语速记、波兰语、加泰罗尼亚语),这就是一个在英语下能编译的文件换一种语言会因为未定义速记而失败的原因。
分类可以亲自查,这是停止猜测最快的办法:\showthe\catcode`\_ 会打印 TeX 给某个字符的那个数,而 \catcode`\_=12 会把它降级成普通字符——verbatim 机制在一个局部组里做的正是这件事,同时还把 \ 变成普通字符,于是那个块里再没有任何东西算转义。
\begin{array}{c|l|l}\text{source} & \text{role in TeX} & \text{to print it} \\\hline \texttt{\textbackslash\%} & \text{comment} & \text{percent} \\ \texttt{\textbackslash\$} & \text{math shift} & \text{dollar} \\ \texttt{\textbackslash\&} & \text{alignment tab} & \text{ampersand} \\ \texttt{\textbackslash\#} & \text{parameter} & \text{hash} \\ \texttt{\textbackslash\_} & \text{subscript} & \text{underscore} \\ \texttt{\textasciicircum} & \text{superscript} & \text{caret} \\ \texttt{\textasciitilde} & \text{active} & \text{tilde} \\ \texttt{\textbackslash\{\ \textbackslash\}} & \text{grouping} & \text{braces}\end{array}
同一个字符为什么在数学与文本里行为不同
类别码不随模式改变,但 TeX 对哪些类别码动手会变。^ 和 _ 只在数学里被解释;在文本模式里它们被丢掉,这就是不加转义写成 sum\_i.cfg 的文件名会静默丢下划线、连错误都不报的原因。对齐字符 & 相反:它在两种模式里都算数——数学里是 aligned、array、matrix,文本里是 tabular 和 align——而在任何对齐之外,它产出 TeX 最字面的一条消息:Misplaced alignment tab character &.
% 是无条件的:注释字符在数学里、在表格单元格里、在参数内部、在所有地方都结束本行。这让未转义的百分号成为十个里破坏力最大的一个,因为它的损害发生在哪一行根本看不出来:50% of cases 删掉本行余下的部分,于是早先打开的 \{ 在 TeX 读到下一行时仍未闭合,而错误信息指向完全无关的位置。
$ 就是模式开关本身,所以一个多余的美元号不会「印错」——它改掉其后一切东西的规则,经典症状是许多行之后关于 Math formula 或 Misplaced } inserted 的抱怨。{ 与 } 在两种模式里分组,却哪种模式都不打印;要在数学里印出它们需要 \{ 和 \},它们带数学开与数学闭的定界符编码,因此能随 \left/\right 一起缩放;只要符号本身则用 \lbrace/\rbrace。
# 是一个参数标记,只在定义的内部才会被期待。两个值得知道的后果:\newcommand 里一个字面的 # 必须写成 ##,因为扫描定义体时会剥掉一层;LaTeX 的 expl3 接口使用满是下划线和冒号的 \csname 式名字,这就是那些文档把一切包进 \ExplSyntaxOn 的原因——那是一次类别码改动,不是字体选择。
\{\,x \in \mathbb{R} : x_{i}^{2} \le 1\,\} \quad R \sim S \quad a \mapsto b
\{ 与 \} 是定界符;同一份源码里用于分组的花括号是看不见的。\documentclass[10pt]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{textcomp}
\usepackage{amsmath}
\usepackage{siunitx}
\usepackage[utf8]{inputenc} % harmless today, required on older installs
\begin{document}
\section*{Money, measures and percentages}
The invoice reads \$1{,}250.00 for the item, \texteuro 480.00 for the
delivery and \pounds 12.50 in tax; \SI{45}{\percent} of the budget is gone.
The \texttt{siunitx} route keeps quantity and unit together, so a line break
cannot put the number at the end of one line and the sign on the next.
\section*{Special characters inside maths}
The braces below are \emph{printed}, because \verb|\{| and \verb|\}| carry
math-open and math-close delimiter codes rather than grouping:
\[
\mu(A \cap B) \le \min\{\mu(A), \mu(B)\}, \qquad
\{x : \lvert x\rvert < 1\}
\]
Grouping and printing are different jobs: \verb|{a,b}| on its own would
vanish, and \verb|\left\{ ... \right\}| sizes the braces to the content.
Subscripts and superscripts are the whole reason \verb|_| and \verb|^| cannot
be typed in maths, and \verb|\&| is legal only at an alignment tab:
\[
\begin{aligned}
a_{ij}^{2} &= \sum_{k} a_{ik} a_{kj}^{2} \\
b_{1} &= 2a_{1} - 3
\end{aligned}
\]
\section*{A heading is a moving argument}
% \verb inside \section fails: the argument is written to the .toc file.
\section{Files named \texttt{final\_v2.tex}}
To keep verbatim material in a heading you need the \texttt{cprotect}
package, or you accept \texttt{\textbackslash texttt\{...\}} with an escaped
underscore, as above.
\end{document}
重音:命令、字母,以及底下的编码
重音命令都带一个参数,覆盖整个拉丁字母表:\'{e} 尖音符、\`a 重音符、\^o 抑扬符、\"u 分音符或变音符、\~n 波浪号、\v{c} caron(háček)、\c{c} 下加字符、\.{z} 上点、\u{g} 短音符、\={a} 长音符、\b{o} 下划线、\d{n} 下点、\H{o} 双尖音符、\r{a} 上环、\k{a} 下加钩、\t{oo} 连字弧。不算重音的字母有自己的命令:\o/\O、\l/\L、\ae/\AE、\oe/\OE、\aa/\AA 和 \ss,再加上 \i 与 \j,手工在 i 上组合符号时就靠这种无点形式。大写尖 s 在 Unicode 里存在,但传统的 8-bit 文本字体没给它留字位——这也是这个字符要等 XeLaTeX 或 LuaLaTeX 的众多理由之一。
这些命令产出的是单个字形还是拼装件,由字体编码决定,这也正是 OT1 与 T1 之间最实际的差别。在 T1 下,配 \usepackage[T1]{fontenc} 和一个确有这些字位的字体,\'e 就是预组合好的 é:断词器能在词内断开,读者能把它从 PDF 里复制出来,小型大写也能拿到带重音的字形。在 OT1 下,重音是在输出时叠在字母上的,于是那个位置无法断词、文本抽取出来是两个字符,而某些字形干脆不存在。自 2018 年那次发布起,UTF-8 就是 LaTeX 的默认输入编码,所以只要载入了 T1,在 pdfLaTeX 下直接敲 é 也行——重音命令仍然有用,因为写 \'e 的源码能扛住把编码弄坏的编辑器。
缺字形是被报告出来,不是被编造出来:日志里那行 Missing character: There is no ż in font cmr10 是一条字体抱怨,按顺序的解法是 T1 或包含该字符的那个编码、用 \usepackage{lmodern} 换取更宽的 Latin Modern 覆盖,或者当字符完全在 8-bit 世界之外时改用 newtxtext/XCharter/fontspec。土耳其语和波兰语是经典的坑,因为带点与不带点的 I 是区别意义的(\i、\I、\k{a}),而字位不够的字体在 pdfLaTeX 下会静默替换,在 XeLaTeX 下不会。
数学有一套自己的重音,完全独立:\hat、\widehat、\tilde、\widetilde、\bar/\overline、\vec、\dot、\ddot、\check、\breve、\acute、\grave 和 \mathring。它们是把重音摆放到一个数学原子上的操作,不改变字母的符号类,而 \hat{\gamma} 与 \gamma 在你给它加粗或缩放时并不是同一个对象——这也是下面链接的那页数学重音参考存在的原因。
\acute{e} \quad \grave{a} \quad \hat{o} \quad \check{c} \quad \tilde{n} \quad \bar{a} \quad \dot{x} \quad \ddot{u} \quad \mathring{a} \quad \breve{g}
不算特殊、但仍有正确写法的标点
引号是最扎眼的新手标志:ASCII 的 " 是直双引号,而正确的排版用两个反引号开、两个撇号闭,所以源码 ``like this'' 产出配对的弯引号,`like this' 产出单引号形式。嵌套引用每边要四个字符。记不住的话,csquotes 宏包提供 \enquote{...},并且通过 babel 一并处理法语和德语的引号惯例。
破折号是三个不同的字符:- 是词内的连字符,-- 是用于区间的短破折号(2019--2024、pp.~12--18)兼数学减号,--- 是用于插入语的长破折号。三个手打的句点仍然是三个句点并带一个句末空格因子;文本里的省略号是 \ldots,数学里是 \dots,而在数学里位置还要紧——amsmath 的 \dotsc、\dotsb、\dotsm、\dotsi 会按后面跟着什么,把点放在数学轴上或基线上。
货币是那种「转义技术上没错、排版上偏弱」的情形:\$100 打印的是文本字体里的 ASCII 美元字形。正规字形是 textcomp 的 \pounds、\texteuro、\textdollar;结构性的答案则是把数值、空格与符号放进同一个对象——百分数用 \SI{45}{\percent},金额用 siunitx 的货币支持——这样断行就无法把数字与符号分开的。
句间距是这一族的最后一项,而且是一个真实的机制:句点之后 TeX 抬高 \spacefactor,随后的空格更宽——在句末这是对的,在 Mr. Smith、1. Introduction、i.e. hence 里就是错的。解法是一个显式的控制空格(Mr.\ Smith)、一对把句点从扫描器面前藏起来的花括号(Mr.{}),或者给以词收尾的宏使用 xspace 宏包。
排不掉的材料:verb、verbatim 与 detokenize
在一段代码样例里手工转义十二个字符,比原问题更糟。\verb|...| 是行内的答案:两个相同定界符之间的一切原样打印,空格保留,既不转义也不解释命令。所有限制都来自它的实现方式(一个活动的定界符字符加上类别码改动):| 不能当含有 | 的那串的定界符;\verb 不能出现在另一个命令的参数里,所以小节标题、图题、脚注和任何移动参数里都不能有 \verb;它也不能跨越段落。
verbatim 在自己的环境内解除这些限制,于是 \begin{verbatim}...\end{verbatim} 可以容纳任何东西——但这个环境本身仍然是一条命令,所以它不能嵌套在另一个命令的参数里,其内容也不能包含一行正好是 \end{verbatim} 的东西。带星号的 verbatim* 在移动参数内部时会把材料挡在 .aux 之外,而 \begin{verbatim} within a file you plan to \\input 是安全的,因为那块内容由同一套类别码机制读入。
凡是需要样式、边框或行号的,工具是 listings:它有自己的(更弱的)转义规则、保留空格,还能做高亮。在普通散文里,退路是逐字符手工转义的 \texttt{},以及朴素 TeX 的 \string\frac——它打印控制序列名的那些字符而不是执行它,任何需要展示自己的输出的宏背后都是这一招。
有一个坑在这三者里反复出现:\ 在 verbatim 块内是普通字符,所以那个块不能包含你选的定界符;更重要的是,块里的 \end{verbatim} 会被读成环境的结束。如果你的样例必须包含字面的 \end{,就选 listings,它读入内容的方式不同。
% Listings of un-typesettable material: the four tools, weakest first.
\documentclass[11pt]{article}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{amsmath}
\usepackage{verbatim}
\usepackage{listings}
\begin{document}
One character or one short run inside a sentence: \verb|a_b#c|, and with a
different delimiter so that a bar can be printed, \verb+#&_|+.
A whole block, unsanitised:
\begin{verbatim}
for i in range(10): # % $ & _ { } ^ ~ all arrive untouched
print(f"{i}\t{i^2}")
\end{verbatim}
The starred form \verb*|trailing space | is the one that shows blanks as
visible boxes, which is what you want when the point of the sample is a
space. The \verb|verbatim| environment cannot appear inside another
command's argument, and \verb|\verb| cannot appear in a section heading, a
caption or a footnote: those arguments are moved, and \verb|\protect| does
not rescue either of them. For code that needs a frame, a language or line
numbers, use the \texttt{listings} package:
\begin{lstlisting}[basicstyle=\ttfamily\small,frame=single]
SELECT a, b FROM t WHERE a LIKE '%x_' -- % and _ stay literal
\end{lstlisting}
One asymmetry to remember: inside \texttt{lstlisting} the percent sign is
still just a character, but the environment reads its own closing line, so a
sample that has to contain \verb|\end{lstlisting}| needs a different tool.
\end{document}
拉丁之外的字符:引擎、编码,以及必须存在的字体
一个非拉丁字符要出现在页面上,三层必须一致:文件里的字节(默认 UTF-8)、字体被选用的编码,以及一个真的拥有该字形的字体。pdfLaTeX 在这儿能干实事,但每种文字都需要自己的编码表和自己的字体——西里尔用 T2A 配 lh 系列,希腊文用 LGR 配 cbgreek 字体——再加上一个会连带搬动断词与拼写规则的 babel 语言:\usepackage[T2A,T1]{fontenc} 与 \usepackage[russian,english]{babel},之后 \foreignlanguage{russian}{\dots} 就能只切一段文字。
其余的一切——中日韩文字、阿拉伯文与希伯来文、天城文、IPA、emoji——8-bit 那条路是死胡同,答案是 Unicode 引擎:XeLaTeX 或 LuaLaTeX 配 fontspec,再加 polyglossia 或新版 babel 来处理语言相关的行为。在那里字符是按名字从你指向的 OpenType 文件里取的,断词与书写方向来自语言模块,而 \newfontfamily\cjkfont{Noto Serif CJK SC} 是一行代码而不是一个编码工程。双向文本同样要走这条路:bidi 是在那些引擎里实现的,不在 pdfLaTeX 里。
失败方式永远是那两种,两种都是日志消息。Missing character ... in font 说明编码没问题、字体有问题:换覆盖面更宽的字体,或换一个 OpenType 覆盖对得上的字体。Package inputenc Error: Unicode character … not set up for use with LaTeX 正好相反:字体也许有那个字形,但 8-bit 输入层里不存在映射,这就是 pdfLaTeX 那堵墙——翻过去靠换引擎,而不是再找一个宏包。
有一种混合情形值得点名,因为它在科技文本里最常见:某个在任何文本字体里都不存在的符号——对勾、箭头、约等号。数学字体带着其中许多(amssymb 的 \checkmark、\leftarrow 一类),所以在文本宏里写 \ensuremath{\checkmark} 是正当的用法;也正因为数学里没有那些,才有 pifont 的 \ding{51} 与 \ding{55}。
那张表,以及终结大多数这类 bug 的三条规则
本节那份清单把一个可编译文件里的整套转义集装在一起:八个反斜杠转义、三条 \textasci… 命令、textcomp 里竖线与尖括号的补充、每个重音命令对着自己的输出、一个用来打断连字的 \textcompwordmark,还有两个用 \verb 引住的文件名,好让它们的下划线和反斜杠活下来。把它当作一份文档的起点,而不是一页要滚动看完的东西。
规则一:当一个字符消失、被替换、或把你的行注释掉时,它是那十个之一,解法是那个字符的转义,而不是某个宏包。规则二:当一条关于字符的错误提到字体或类别码时,它不是那十个之一,解法在编码、引擎或字体。规则三:当那段文本是代码而不是散文时,根本别去转义它——用 \verb、verbatim 或 listings,按它是否需要活在参数里来选。
无视这三条就会出现错误清单里那两种失败:一个百分号吃掉行尾、两行之外才报错;以及一个未转义的 & 或 # 被 TeX 当成真实的请求——前者在表格单元格里,于是报出一个错误的列数;后者在 \newcommand 的定义体里,于是要求把 # 写成双份。
如果你的文档把这些混在一起——货币、几个带重音的姓名、一段代码、一句西里尔引文——那就用 UTF-8 写、载入 T1 配 lmodern、让 amssymb 和 textcomp 随时可用,并用 latexmk 编译。本页的三份清单都是在这套导言下完整的文件,照原样就能编译。
\documentclass[11pt]{article}
\usepackage[T1]{fontenc} % precomposed accented glyphs, hyphenation works
\usepackage{lmodern} % a vector font with the T1 glyphs filled in
\usepackage{textcomp} % \texteuro, \textbar, \textless, \textcompwordmark
\usepackage{amssymb} % \checkmark
\usepackage{hyperref}
% UTF-8 input has been the default since the 2018 LaTeX release, so this
% document can contain é, ç, ø and 漢字 directly; the \accent forms below are
% shown because they still work and because diffs are easier to read.
\begin{document}
\section*{The escapes}
100\% of the invoice is \$100; the contract is between Smith \& Jones; the
file \verb|report_final.pdf| lives in
\texttt{C:\textbackslash tmp\textbackslash work}. Note the caret
\textasciicircum, the tilde \textasciitilde, the grave \textasciigrave, the
bar \textbar{} and the angle brackets \textless x \textgreater.
Curly braces need a backslash: \{ \} --- and the em dash is three hyphens,
the en dash two. Quotation marks open with two backticks and close with two
apostrophes: ``like this'', and a single quote is `like this'.
\section*{Accents, both routes to the same glyph}
The left column is quoted with \verb|\verb| so that it prints as source; the
right column is the same characters let through by the encoding layer.
\begin{tabular}{@{}ll@{\hspace{2em}}ll@{}}
\textbf{Source} & \textbf{Result} & \textbf{Source} & \textbf{Result} \\
\verb|\'e| & \'e & \verb|\={a}| & \={a} \\
\verb|\`a| & \`a & \verb|\b{o}| & \b{o} \\
\verb|\^o| & \^o & \verb|\d{n}| & \d{n} \\
\verb|\"u| & \"u & \verb|\H{o}| & \H{o} \\
\verb|\~n| & \~n & \verb|\r{a}| & \r{a} \\
\verb|\v{c}| & \v{c} & \verb|\u{g}| & \u{g} \\
\verb|\c{c}| & \c{c} & \verb|\k{a}| & \k{a} \\
\verb|\.z| & \.z & \verb|\t{oo}| & \t{oo} \\
\verb|\o| & \o & \verb|\L| & \L{} \\
\verb|\ss| & \ss & \verb|\ae| & \ae \\
\verb|é ç ø í| & UTF-8 input & \verb|f\textcompwordmark i| & no ligature: f\textcompwordmark i \\
\end{tabular}
\section*{Where they bite}
A percent sign with no backslash comments out the rest of the line, so an
unclosed brace two lines later is the error you get: % this is invisible now
Ampersands belong to tables: \& in prose, and in maths only inside an
alignment. A hash sign outside a macro definition is never what you meant,
and inside a \verb|\newcommand| body a literal hash has to be doubled.
\end{document}
本课速查
每节抽一行关键代码:点小节名跳到对应位置,代码一键复制。
\begin{array}{c|l|l}\text{source} & \text{role in TeX} & \text{to print it} \\\hline \texttt{\textbackslash\%} & \text{comment} & \text{percent} \\ \texttt{\textbackslash\$} & \text{math shift} & \text{dollar} \\ \texttt{\textbackslash\&} & \text{alignment tab} & \text{ampersand} \\ \texttt{\textbackslash\#} & \text{parameter} & \text{hash} \\ \texttt{\textbackslash\_} & \text{subscript} & \text{underscore} \\ \texttt{\textasciicircum} & \text{superscript} & \text{caret} \\ \texttt{\textasciitilde} & \text{active} & \text{tilde} \\ \texttt{\textbackslash\{\ \textbackslash\}} & \text{grouping} & \text{braces}\end{array}
\documentclass[10pt]{article}
\acute{e} \quad \grave{a} \quad \hat{o} \quad \check{c} \quad \tilde{n} \quad \bar{a} \quad \dot{x} \quad \ddot{u} \quad \mathring{a} \quad \breve{g}
\documentclass[11pt]{article}
常见错误
- 行文或公式里一个光秃秃的
%:它把本行余下部分注释掉,于是 TeX 报的错误落在后面某一行、关于一个未闭合的花括号。写\%。 - 在散文里打
&,然后把Misplaced alignment tab character &读成表格的 bug。对齐之外这个字符是非法的,答案是\&。 \newcommand定义里一个字面的 #:定义体是按参数记号扫描的,所以 # 必须写成##。普通文本里则是\#。- 指望
\_在数学里也能用。它是文本模式的命令,要在数学里印这个字符得走\text{\_}(amsmath)——反过来那一点也要记着,因为行文里光秃秃的_是被静默丢掉,而不是排成一个下划线。 - 把
\verb|...|放进小节标题、图题或脚注:它在移动参数里不 robust,要么用带转义的\texttt{},要么加载cprotect。 - 引号打成
"this"、破折号打成-,然后怪字体。``this''、--和---才是预期的写法。 - 在现代发行版上加
\usepackage[utf8]{inputenc}去治重音字母的问题:UTF-8 早就是默认值,真正的缺口通常在字体编码——\usepackage[T1]{fontenc}配lmodern。
关于本课的常见问题
LaTeX 里百分号怎么打?
LaTeX 里下划线怎么打?
\text{\_}。^ 与 \textasciicircum 之间也是同样的不对称。为什么 LaTeX 说 misplaced alignment tab character?
怎么在 LaTeX 里写 é、ñ 这类重音?
\hat、\tilde、\bar、\vec、\dot、\ddot、\check、\breve、\mathring。怎么在 LaTeX 文档里打印 LaTeX 代码?
\verb|...|,成块的放进 verbatim 环境,需要边框、行号或语言高亮的放进 listings。要记住的限制是 \verb 不能活在另一个命令的参数里,所以标题、图题和脚注得改用带转义的 \texttt{...}。为什么我的小于号在 PDF 里不见了?
\usepackage[T1]{fontenc} 配 lmodern,或者用 textcomp 里不依赖编码的 \textless 与 \textgreater。数学里这两个符号是 \lt 和 \text{<},不是原字符。实时演示:直接编辑 LaTeX,立刻看渲染结果
预览随输入实时更新——不妨故意写坏一次,看看报错长什么样。
继续读
同一个东西的三个入口:记法本身、讲它的那一课、以及真正用它写东西的一篇文章。