阶段 1 · 零基础起步 6 / 48 ≈ 13 分钟读完

LaTeX 模板怎么用才不写坏:cls、sty 与选项冲突

LaTeX 模板不是「套上样式的文档」,而是在你的正文之前运行的一段代码——这正是改它让人心里发虚的原因。这里讲清类文件与宏包文件到底改了什么、LaTeX 按什么顺序去找它们、随附文件里你有权动哪几行,以及几乎每一次投稿卡住所出自的那五处破损。

    模板是由什么组成的

    一份 LaTeX 模板是一组文件,它们在你的正文被读到之前重新编程了排版器。.cls 是文档类:页面几何、字体、标题尺寸,以及哪些命令根本存在,都由它决定。.sty 是宏包,在文档里用 \usepackage 加载,负责新增或覆盖行为。.bst 对参考文献干的是同一件事,而且它属于完全另一门语言(BibTeX 自己的),这就是为什么修引用格式永远用不到 TeX 命令。

    类与宏包的分别最值得内化,因为两种失败长得很像、修法却不同。\documentclass{llncs} 表达的是「这个程序跑起来之前并不存在一份文档」;那个文件不在,LaTeX 会立刻停在 ! LaTeX Error: File `llncs.cls' not found. 一个缺失的 .sty 会在晚一行的位置产生同样形状的信息。两种情况的补救都是让文件可被找到,而不是去改你的正文。

    「可被找到」有精确含义,而查找顺序解释了模板最常见的奇迹:把文件放在 .tex 旁边就好了。LaTeX 先搜工作目录,再看 TEXINPUTS 里的额外路径,然后是个人树(TEXMFHOME),最后才是发行版树。所以导师邮件发给你的类文件,一放进项目目录当场可用;而装在发行版深处的 .cls,会被你源码旁边那一份旧拷贝整个遮住。

    kpsewhich 是把这件事从民间经验变成一次检查的仪器:在项目目录里跑 kpsewhich myclass.cls,它会精确打印 LaTeX 将要使用的那个文件,或者什么都不打印。在怀疑模板有 bug 之前,先用它。

    Which copy of a class or style file LaTeX actually loads, and where to install a file you were sent the request \documentclass [conference]{venue} search order, first hit wins 1 · the folder you are compiling in ./venue.cls ← v1.0, sent by email 2 · TEXINPUTS / TEXINPUTS.$format set by an editor, a project or CI 3 · TEXMFHOME — your own tree safe place for a template you reuse 4 · TEXMFLOCAL, then TEXMFDIST texlive/2025/texmf-dist ← v2.3 the trap this creates Two copies on one machine. LaTeX loads the one nearest your file, which is the older one, and never mentions it. kpsewhich venue.cls → ./venue.cls ← the answer is the diagnosis delete, rename or version the shadowing copy, then prove what the run used with the file list from \listfiles. "Works on my machine, wrong layout on theirs" = this box. Same rule for .sty, .def, .cnf and .bst files. where to install a template you keep using kpsewhich -var-value TEXMFHOME # C:\Users\you\texmf or ~/texmf <TEXMFHOME>/tex/latex/venue/venue.cls <TEXMFHOME>/tex/latex/venue/venue.sty <TEXMFHOME>/bibtex/bst/venue/splncs04.bst mirror the distribution's own layout inside tex/type/package/ — that is what makes the lookup succeed without a TEXINPUTS edit then: mktexlsr MiKTeX: refresh the file name database. skipping this is the #1 follow-up
    文件是按固定顺序被搜索的,所以项目目录里的那份拷贝永远赢过随发行版安装的版本。

    动手改之前,先把模板读一遍

    模板到手通常是一个 zip:一个 .cls、两三个 .sty、一到两个 .bst、一份示例文档(多半叫 template.tex 或 sample.tex),以及一份没人打开的 readme。第一个动作是按随附状态原样编译示例,一点都不改,确认你拿到的 PDF 与出版社页面上展示的那份一致。这一步就失败的话,你后面做什么都没用——遇到的是文件缺失或引擎错的问题。

    然后读三行。第一行 \documentclass[...]{...}:那个选项列表是一份合同。期刊类会读 conference、final、draftcls、twocolumn、10pt 这类选项,改动它们会改变页数,有时直接改变你的投稿能否被接收。第二行是 \documentclass 与 \begin{document} 之间的宏包清单:那是模板假定存在的东西集合,也是判断正文里哪些命令合法的线索。

    第三,找出这个类要求的命令。有些是从 article 继承的——\title、\author、\maketitle、\begin{abstract}。许多是模板自创的:\keywords{...}、\institute{...}、\classification、\ead{a@b.edu}、\setcopyright{}。前者中被要求却留空的,会让收稿台以首页空白为由退回你的 PDF;后者用在了错误的类上,则会让 ! Undefined control sequence. 出现在一份你从没写过的文件的第 4 行。

    示例文件一般会用一个注释标出边界,例如 % %% Put your text here,或者把演示材料包进 \iffalse ... \fi,让它作为被跳过的文本读入。找到那条边界,并且把它当围栏来对待。

    让你不惹麻烦的那套流程

    按固定顺序做,任何模板问题都会变成小问题。(1) 解压到它自己的目录,不重命名任何文件。(2) 原样编译示例。(3) 把示例正文一节一节换成你自己的,每换一节重编一次,于是每次失败的可疑窗口只有十五秒。(4) 把你自己的宏包移进模板唯一允许的位置——紧跟它自己的 \usepackage 那一块之后、\begin{document} 之前。(5) 最后才处理参考文献。

    两条规则挡住大多数损坏。不要删你解释不了的那一行。一句诡异的 \renewcommand{\footnotemark} 或 \setlength{\textfloatsep}{9pt} 是承重的,你会在凌晨两点发现这一点。不要加纵向间距。不要 \vspace、不要空的 \line、段落之间不要 \\:双栏类的页数是有人会动手检查的上限,而手工挪动会一路传到后面三页。

    需要模板不提供的行为时,把它加成新的宏,而不是去改类文件。在导言区写 \newcommand{\dn}[1]{\textcolor{red}{#1}},而不是到 .cls 里翻找某个颜色定义来改。日后你需要证明源码是未经修改的模板——某些期刊确实会要——一份只动了自己文件的 diff 就是一场轻松的对话。

    模板要用的部件保持成独立文件,别粘进主文档:类允许的话用一个 \input{preamble-local},图片放进 fig/ 并配一句 \graphicspath{{fig/}},references.bib 挨着类文件放。模板加你自己的三个文件是一个项目;模板加上粘进去的 400 行则是一份化石地层记录。

    Which parts of a shipped LaTeX template you may edit and which you must leave alone a shipped main file, band by band \PassOptionsToPackage{dvipsnames}{xcolor} yours — the only \documentclass[conference,10pt]{venue} theirs — options too \usepackage{amsmath} ... (their package list) theirs — read it \usepackage{your-needed-package} % after theirs yours — before \begin \title{}\ \author{}\ \keywords{}\ \begin{abstract} fill in, do not restyle \section{Introduction} As shown in Figure~\ref{fig:a}, ... \begin{figure*}[t] ... \caption{} \label{} \end{figure*} \begin{equation} ... \label{eq:k} \end{equation} ... your whole text, figures, tables, maths ... yours two-column page? widen a float with the starred form, never shrink text \bibliographystyle{venue}\ \bibliography{refs} style is theirs venue.cls venue.sty splncs04.bst never edit these the three verdicts write here freely your prose, your macros, your own packages added after theirs your figures in a tracked folder fill in only the title block, the abstract, the keywords — structure fixed by the class, contents entirely yours do not touch the class line, its options, its package list, the .cls / .sty / .bst files, and the page geometry Need something outside the green band? define a new macro in your preamble — or ask the editor.
    随附文件的红绿灯:导言区和类拥有版式,你拥有正文和你自己的那些宏。
    % main.tex —— the shape nearly every journal template forces on you.
    % Rule of thumb: the preamble belongs to the template, the body belongs to you.
    \documentclass[twocolumn,10pt,a4paper]{article}   % <- the venue's line: do not edit
    
    \usepackage[T1]{fontenc}
    \usepackage{amsmath,amssymb}
    \usepackage{graphicx}
    \usepackage{booktabs}
    \usepackage[numbers,sort&compress]{natbib}       % many classes want this exact form
    \usepackage{caption}
    \captionsetup{font=small,labelfont=bf}           % the venue's caption style
    \usepackage[colorlinks=true,citecolor=blue]{hyperref}  % load it last
    
    \begin{document}
    
    \title{A Two-Column Example That Mimics a Conference Class}
    \author{A. Student\thanks{Department of Something, University of Where.
            Email: \texttt{a.student@example.edu}}}
    \date{\today}
    \maketitle
    
    \begin{abstract}
    \noindent
    The abstract is a single paragraph with no indentation, no displayed
    equations and no citations in most templates. Fill it in; do not restyle it.
    \end{abstract}
    
    % ============================================================
    %  EDIT BELOW THIS LINE -- everything above belongs to the template.
    % ============================================================
    \section{Introduction}
    Write here. Keep the sectioning commands the class provides, and add
    no \verb|\vspace| to push things around: page count is the reviewer's
    business, not yours.
    
    A displayed formula in one column of a two-column page has about
    0.47 of the text width to live in, so this one needs splitting:
    \[
      \underbrace{\sum_{i=1}^{n} \left(x_i - \bar{x}\right)^{2}}_{\text{one line}}
      \;=\;
      \underbrace{\sum_{i=1}^{n} x_i^{2} - n\bar{x}^{2}}_{\text{the other}}
    \]
    
    \section{Conclusion}
    Cite with \verb|\cite| and never type a reference by hand:
    an unnumbered bracket is the fastest way to look sloppy~\cite{knuth84}.
    
    % ============================================================
    %  EDIT ABOVE THIS LINE.
    % ============================================================
    \begin{thebibliography}{9}
      \bibitem{knuth84} D.~E. Knuth, \emph{Computers and Typesetting}, 1984.
    \end{thebibliography}
    
    \bibliographystyle{unsrtnat}   % the class may demand a specific .bst
    \bibliography{references}      % harmless if references.bib is absent
    \end{document}

    选项,以及随之而来的冲突

    一个选项只能被看见一次。宏包会记住自己是被哪些选项加载的,如果类已经写过 \RequirePackage{xcolor},而你又写了一遍 \usepackage[dvipsnames]{xcolor},LaTeX 就拒绝用另一套选项第二次加载它,并打印 ! Option clash for package xcolor. 信息会点出宏包名,这已经是诊断的全部;剩下的只是知道下面那一招。

    那一招是在类看到这个宏包之前,先把选项递过去。把 \PassOptionsToPackage{dvipsnames}{xcolor} 写成 \documentclass 上面的一行。于是宏包只被加载一次、带着两边选项的并集,冲突消失。同一行也能修掉更烦的那种变体:第二次加载什么都没做,你的选项于是被静默忽略。

    第二种常见冲突是 geometry。自己设定页边距的类通常已经加载过 geometry;你再加一句 \usepackage[a4paper,margin=2cm]{geometry},轻则选项冲突,重则你如愿拿到想要的纸型、外加一次退回,因为页眉跑位了。如果模板并没有加载 geometry 而你还是想要别的页边距,那你是在修改模板,不是在使用它——先决定自己到底在玩哪个游戏。

    第三类是纯粹的功能缺失:hyperref 之后才 \usepackage{cleveref}、类重定义了 \labelitemi 却又要 \usepackage{enumitem}、或者在已经定义定理环境的类里塞进 amsthm。通用的加载顺序规则很少,值得背下来:inputenc/fontenc 靠前,hyperref 接近最后,cleveref 排在 hyperref 之后。其余的先后都随意。

    \bigl\lVert \mathbf{A} \bigr\rVert_{2} = \sigma_{\max}(\mathbf{A})
    \bigl\lVert \mathbf{A} \bigr\rVert_{2} = \sigma_{\max}(\mathbf{A})
    这里没有任何生僻东西:\bigl、\bigr、\lVert 全都来自 amsmath/amssymb。如果一份类文件不带它们,同一行就会以 Undefined control sequence 失败——那是缺一个宏包,不是缺一份技能。

    真正会出问题的五件事

    1. 一份从没发给你的文件报 File `something.sty' not found。模板依赖某个出版社以为你手里有的宏包。先找归属(tlmgr search --global --file "/something.sty",或 MiKTeX Console 里的包搜索),把它装上;确有必要时拷一份进你自己的树并重建数据库。不要把它拷进发行版树,更不要把宏包源码粘进你的文档。

    2. \keywords、\institute 或 \affil 处报 ! Undefined control sequence.命令属于随附的那个类,而你在拿错的类编译——因为你的 \documentclass 那行还写着 article,或者类文件没在你真正构建的那份文件旁边,或者你编辑的是子目录里的拷贝、而编辑器编的是根目录那一份。这是一个穿着语法错误外衣的文件位置问题。

    3. 首页出来不对:作者挤成一团、没有单位、\thanks 不见了。多作者块是 LaTeX 里标准化程度最低的部分。article 里作者之间用 \and 分隔,不是逗号、也不是 \\;用 authblk 的类要 \author[1]{...} 配 \affil[1]{...};LNCS 要 \and 加 \institute{...}。照抄随附示例里的写法而不要自己发明,并且把人名里的重音写成 \'e 这类形式或正确的 UTF-8——作者列表里一个坏掉的 é,是论文集印出来之后代价极高的一个笔误。

    4. 参考文献全部出来是 [?]。四个原因,按顺序:你只编了一遍,而不是必需的 LaTeX → BibTeX/Biber → LaTeX → LaTeX;\bibliographystyle{...} 那行点了一个并未安装的 .bst;\bibliography{...} 的路径不对;或者引用键拼错、而真正的信息在 .blg 里。注意所有引用都是 [?] 说明是流水线问题,只有一个是则说明是键名问题——这个区分能省一小时。

    5. 文档多出一页,或者一张图就是放不下。双栏类里,单栏的展示公式大约只有文本宽度的一半可住,所以长式子必须用 \begin{aligned} 拆成几行,或者升级为跨双栏的浮动体 \begin{figure*} 与 \begin{table*}——它们横跨两栏并浮到页面顶部。永远不要靠缩字号去换空间:缩图,不要缩字体,也永远不要设一个类根本没有提供的字号。

    \sum_{i=1}^{n} \left( x_{i} - \bar{x} \right)^{2} = \sum_{i=1}^{n} x_{i}^{2} - n\bar{x}^{2}
    \sum_{i=1}^{n} \left( x_{i} - \bar{x} \right)^{2} = \sum_{i=1}^{n} x_{i}^{2} - n\bar{x}^{2}
    \tilde{a} \quad \hat{b} \quad \bar{x} \quad \vec{v} \quad \dot{y} \quad \Gamma
    \tilde{a} \quad \hat{b} \quad \bar{x} \quad \vec{v} \quad \dot{y} \quad \Gamma
    # 1. Can the engine see the file at all? (print the path, or nothing)
    kpsewhich myconference.cls
    kpsewhich splncs04.bst
    kpsewhich -var-value TEXMFHOME       # your personal tree
    kpsewhich -var-value TEXINPUTS       # extra search path, if any
    
    # 2. Which files does the run actually read? (-recorder writes .fls)
    latexmk -pdf -recorder -interaction=nonstopmode main.tex
    grep -i "cls\|sty" main.fls | sort -u | head -40
    
    # 3. TeX Live: find the package that owns a missing file
    tlmgr search --global --file "/splncs04.bst"
    tlmgr install <the-package-name-it-prints>
    
    # MiKTeX: search the package list in the Console, install it, then
    # Maintenance -> Refresh file name database.  Skipping the refresh is why
    # a clearly-installed file is still reported as not found.
    initexmf --update-fndb
    
    # Put a received template in your OWN tree, never inside the distribution:
    #   <TEXMFHOME>/tex/latex/myconference/myconference.cls
    #   <TEXMFHOME>/bibtex/bst/myconference/splncs04.bst
    # then run  mktexlsr   (TeX Live) or refresh the FNDB (MiKTeX).

    自己写一个类,比你想的便宜

    如果你每周都在和模板搏斗——一套有内部格式要求的学位论文、一个实验报告系列、一份份试卷——那就写一个小类,而不是一份到处粘贴的导言区。类文件就是普通 LaTeX 加上开头五行:\NeedsTeXFormat{LaTeX2e}、写名字与版本的 \ProvidesClass、每个你接受的选项配一行 \DeclareOption、\ProcessOptions,以及从 article 或 report 继承的 \LoadClass。后面全是你本来就会的 \setlength 与 \renewcommand。

    本页那份清单就是一个完整、可加载的例子:两个自有选项、一条把未知选项转发给 article 的通配、一个个人树的安装位置,外加一处 \linespread 微调。把它当作你自己那份的骨架来读;\DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}} 这一行,就是让派生类行为正常的关键所在。

    把它放到 LaTeX 不需要你操心就能找到的位置:要么紧挨文档,要么在个人树的 <TEXMFHOME>/tex/latex/myconference/myconference.cls,其中 TEXMFHOME 就是 kpsewhich -var-value TEXMFHOME 打出来的路径。TeX Live 之后跑一次 mktexlsr,MiKTeX 则刷新文件名数据库。从此 \documentclass{myconference} 在这台机器的任何项目里都成立,你的五篇论文终于共用同一份页边距定义。

    回报是可复现性,而这才是模板真正的用途。类文件可以被版本管理、被评审、被 diff;粘贴到六份文档里的那份导言区则一定会漂,而漂的结果就是第六份文档在距离截止三周时行距和别人不一样。

    % myconference.cls —— a real, loadable class file in twenty lines.
    % Keep it in the same folder as main.tex and \documentclass{myconference}
    % will find it: the current directory is searched before anything else.
    \NeedsTeXFormat{LaTeX2e}
    \ProvidesClass{myconference}[2025/03/01 v1.0 Tiny conference style]
    
    % ---- our own options, declared BEFORE the fallback ----
    \newif\if@poster
    \@posterfalse
    \DeclareOption{poster}{\@postertrue}
    \DeclareOption{tightlines}{\AtEndOfClass{\linespread{0.97}\selectfont}}
    
    % ---- anything we do not know gets forwarded to the base class ----
    \DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}}
    
    \ExecuteOptions{a4paper}
    \ProcessOptions\relax
    
    \LoadClass{article}
    
    % ---- the actual "look" of the template ----
    \RequirePackage[T1]{fontenc}
    \RequirePackage{microtype}
    \RequirePackage[margin=2.2cm,columnsep=1.4em]{geometry}
    \setlength{\parskip}{0.35em}
    \setlength{\parindent}{0pt}
    
    \if@poster
      \pagestyle{empty}
      \setlength{\parskip}{1em}
    \fi
    
    \renewcommand{\section}{%
      \@startsection{section}{1}{\z@}{-1.2ex}{0.6ex}{\normalfont\large\bfseries}}
    
    \endinput

    Overleaf 上的模板,以及什么时候该停手

    Overleaf 模板库里的模板是同样那组文件,外加一台替你决定引擎的服务器。两处项目设置要紧:Menu → Main document,因为一份模板 zip 里有四个 .tex、而只有一个里面写着 \documentclass;以及 Menu → Compiler 加 TeX Live version,因为为 XeLaTeX 写的类在 pdfLaTeX 下只会产出坏结果,而钉在旧 TeX Live 上的项目会在一个需要更新宏包的语句上失败。

    上传自己的模板就是字面意思:传 zip,设主文档,检查编译器。需要具体引擎参数或 max_print_line 时,在项目根目录放一个 latexmkrc;Overleaf 会读它,本地的 latexmk 也读它,于是同一份文件可以同时承载两处的构建规则。

    镜像的那个错误是过度定制。你在类里改的每一处,都是你必须自证的一处,而说「原样使用我们的模板」的期刊指的就是页面几何、字体和题注样式。需要更长的标题块,解法是在 \title{} 里放一个 \linebreak,或者换一个短一点的标题,而不是重定义 \maketitle。如果模板确实表达不了你要的东西,就直接向编辑说明——那场对话很短,而和论文集办公室就一份不合规范 PDF 的对话并不短。

    一条合理的止损线:给「与模板搏斗」留一个小时。如果示例编得过、而你的内容编不过,那问题就是一个文件或者一个选项,本页靠前几节的诊断手段会点出它。超过这个数,你已经不是在用模板——你在写模板,此时该明确决定的是:截止时间允许不允许。

    本课速查

    每节抽一行关键代码:点小节名跳到对应位置,代码一键复制。

    小节 关键代码
    \documentclass[twocolumn,10pt,a4paper]{article} % <- the venue's line: do not edit
    \bigl\lVert \mathbf{A} \bigr\rVert_{2} = \sigma_{\max}(\mathbf{A})
    # 1. Can the engine see the file at all? (print the path, or nothing)
    \NeedsTeXFormat{LaTeX2e}

    常见错误

    • 把 \documentclass{article} 改成随附的类,类文件却留在子文件夹里,然后把 File `venue.cls' not found 读成模板自身的 bug。
    • 为改一个字号直接编辑 .cls 或 .sty,到重新提交时才发现这份 diff 已经动到了出版社的代码。
    • 用删掉 \usepackage 那一行的方式绕开 ! Option clash for package xcolor——你要的那个选项于是静默地从未生效;正解是 \documentclass 之上的 \PassOptionsToPackage。
    • 多个作者之间用 \\ 或逗号而不是 \and,于是首页把所有名字堆在同一行上。
    • 用 \vspace{-6pt} 加更小字号去换版面,这既破坏了期刊的行网格,也在评审的头三秒就被看见。
    • 拷走随附示例、留着它的 \bibliographystyle,然后纳闷参考文献为何始终不出现在——那里点名的样式文件常常并不是这个类装上的那一个。
    • 用 pdfLaTeX 编一份只有 XeLaTeX 才行得通的模板,只因为那是编辑器的默认;症状是字体不对,而不是一条清楚的错误。

    关于本课的常见问题

    cls 文件和 sty 文件有什么区别?
    .cls 是文档类,由 \documentclass 加载一次,它定义整页版面以及你的文档可以使用的命令。.sty 是宏包,用 \usepackage 加载,用来增加或调整行为。类本身也会加载宏包,选项冲突正是从这里来的:谁先加载一个宏包,谁就替它选定了选项。
    别人发给我的类文件该放在哪儿?
    要么放在含 \documentclass 那份文件的同一个目录——这条永远有效,因为工作目录最先被搜索;要么放进个人树里 kpsewhich 报出的 TEXMFHOME 目录下,然后重建文件数据库。不要装进发行版树,那里一次更新就可能把它带走。
    我的模板为什么报 keywords 未定义?
    因为 \keywords 是模板那个类自创的,而你在拿一个标准类编译。检查 \documentclass 那一行,检查随附的 .cls 是否就在你构建的目录里,再到编辑器里确认哪一个文件才是真正的主文档。
    期刊模板的页边距能改吗?
    能,而且不该改。页面几何是审稿人和制作部门据以校准的东西,改它就改了页数。图或公式真的放不下时,去缩图、去拆公式;如果是整份文档放不下,那是要写给编辑的一句话,不是一行 geometry 参数。
    本地模板怎么在 Overleaf 上用?
    从上传新建项目,选中那个 zip,然后把 Menu -> Main document 设成含 \documentclass 的那份文件,并选模板需要的编译器。在它编译通过之前不要把文件重新归进子目录:许多模板用相对路径引用图片和样式文件。
    为什么我的引用全部显示成 [?]?
    全部坏说明参考文献那一步从未运行、或者样式文件缺失;只坏一个说明那个键和你的 .bib 对不上。跑 latexmk,它会替你排好 LaTeX、BibTeX 或 Biber 以及随后两遍;这类问题要去读 .blg 而不是 .log。

    实时演示:直接编辑 LaTeX,立刻看渲染结果

    预览随输入实时更新——不妨故意写坏一次,看看报错长什么样。

    KaTeX 错误
    试一个例子

    继续读

    同一个东西的三个入口:记法本身、讲它的那一课、以及真正用它写东西的一篇文章。