阶段 4 · 结构与交叉引用 31 / 48 ≈ 14 分钟读完

LaTeX 多文件工程:input、include 与 subfiles 怎么分

把一份文档拆到多个文件不是一个决定,而是四个:用哪条命令纳入文件、用 include 时页面和 .aux 会怎样、一个子文件如何仍能单独编译,以及一旦你的图住在子目录里相对路径会怎么表现。

    这两条命令不能混用

    \input{file} 是一次文本拼接。TeX 会合上当前文件,从命令所在的那个精确位置起逐 token 读 file.tex,然后回到父文件,像什么都没发生过。不分页、不多一个辅助文件、不保存任何状态。它在导言区能用、在表格中间能用、在环境里面也能用——哪儿都行——而且可以随意嵌套,无需多言。宏文件、导言片段、扉页,以及你单独起草的一个段落,都该用它。

    \include{file} 是一条文档结构化命令,它的活儿是把文档切成一块块可各自开关的单元。它的内核定义做了三件 \input 不做的事:先出一道 \clearpage(于是所有悬着的浮动体被安置、页面几何重新起算),往主辅助文件里写一行 \@input{file.aux} 并在读取该文件期间把标签和引文重定向到 file.aux,还会查 \includeonly 列表来决定到底读不读这个文件。

    这三条推论就是整节课。分页自动且无法回避——由 \include 进来的各章组成的文档,绝不会在半页处起一章。标签可以按文件追踪,这正是局部构建能成立的前提。也别指望嵌套:在一个本身被 \include 进来的文件里再放 \include,文档是明令不建议的,而且只有最外层能被 \includeonly 可靠地挑拣——一直好用的模式是章节用 \include、章里面用 \input。同一限制说得更狠:\include 不能待在参数里或环境里,因为它以 \clearpage 开头,而 \clearpage 出现在 tabular 里就是错。

    按结构单元来选,别按大小。用 \include 装那些另起一页、且能被关掉的东西:章节、论文集里的文章、附录。用 \input 装每一个其实是「一个文件戴了顶帽子」的东西:拆成 preamble/packages.tex 和 preamble/macros.tex 的导言区、一张长表、扉页、某一套习题的答案。

    \text{source read} = \sum_{f \in F} \text{lines}(f), \qquad \text{compile time} \propto \text{source read}
    \text{source read} = \sum_{f \in F} \text{lines}(f), \qquad \text{compile time} \propto \text{source read}
    Timeline comparison of input and include: page breaks, auxiliary-file redirection and includeonly behaviour THE SAME THREE FILES, READ TWO DIFFERENT WAYS main.tex \input{a} \input{b} a.tex spliced inline, mid-paragraph if asked b.tex same state as if typed in main one page stream no break, no float flush; text flows across the seam one .aux main.aux holds every label cannot be skipped selectively main.tex \include{a} \include{b} clearpage a.tex starts on a fresh recto in a twoside document clearpage b.tex floats from a are all placed before b begins redirected writes openout a.aux ... a.aux while a is read, labels go to a.aux; main.aux keeps \include clearpage includeonly \includeonly{a} b is not read - but b.aux still resolves its labels WHAT FOLLOWS Choose input for preamble fragments, a title page, one long table, a paragraph drafted separately, anything inside an environment or an argument \input{preamble/macros} \input{tables/results} Choose include for chapters, articles of an edited volume, appendices: units that must start a page and must be switchable. Illegal inside a tabular, an environment, an argument \include{chapters/02-hilbert} \includeonly{chapters/02-hilbert} The cost of includeonly excluded chapters advance nothing, so your chapter becomes 1 and its equations 1.x, and references into them come from the previous full build: plausible, and possibly stale. Full build before sharing, always. grep -c "??" main.log
    同样三个文件,两种读法:input 不动页面也不动辅助文件,include 分页、并给每个单元一份自己的 .aux。

    每文件一份 .aux:给你什么,又收你什么

    当 \include{ch02} 在被读取时,LaTeX 把标签和引文写进 ch02.aux 而不是 main.aux,而这一遍结束时 main.aux 里有一行 \@input{ch02.aux} 又把那些文件拉了回来。.aux 记录 \bibdata 和 \bibstyle 用的是同一个机制,这也是为什么一个多文件项目会在 main.aux 旁边攒出一窝小辅助文件。

    好处是:\includeonly{chapters/02-hilbert} 让 LaTeX 跳过读其他章节,却照样读它们的辅助文件。你正在写的那一章几秒就编完,而伸向别章的每个 \ref 仍然能解析出点什么——在你只改一本两百页书里某一章的时候,你要的正是这个性质。

    代价有两块,两块都是暗刀子。计数器只随着真正被读到的材料前进,所以被排除的章对编号毫无贡献:你正在写的章成了第 1 章,它的公式成了 1.x,总页数少了上百页。而因为指向被排除文件的引用是从它们上一次完整构建的辅助数据里解析的,编号会以一种看着像对的方式过期——\cref{fig:old} 会毫无愧色地从一次早已和正文不符的运行里印出「图 3.4」。纪律是:任何东西在被分享、评审或提交之前先做一次完整构建,并在日志里 grep ??,而不是相信眼前那一页。

    这个开关的实用形状:把 \includeonly{} 作为单独一行注释留在主文件里,让「快速模式」只是一处改动,且绝不用未注释的状态提交。有些项目走得更远,把决定权放进构建命令(经一个包装脚本用 latexmk -pdf -e '$includeonly="ch02"'),让源码保持清白;更简单的习惯是另开一个根文件 draft.tex,只 include 你正在写的部分。

    \underbrace{4.2}_{\text{all chapters read}} \ne \underbrace{1.2}_{\text{only ch01 and ch04 read}}
    \underbrace{4.2}_{\text{all chapters read}} \ne \underbrace{1.2}_{\text{only ch01 and ch04 read}}
    % ============================================================
    % main.tex  —  the only file the compiler is ever pointed at
    % ============================================================
    \documentclass[12pt,a4paper,twoside]{book}
    
    \usepackage{subfiles}           % lets a child also be compiled on its own
    \input{preamble/packages}       % \input, not \include: no page break, no own .aux
                                    % (packages.tex loads amsmath, graphics, hyperref,
                                    %  and cleveref last of all)
    \input{preamble/macros}
    \input{preamble/theoremstyles}
    
    \includeonly{chapters/01-banach}    % selects among \include files; comment it
                                        % out before building anything you share
    
    \begin{document}
    
    \frontmatter                      % book only: roman numbers, restarts at i
    \input{frontmatter/titlepage}       % a \input file with no \begin{document} of its own
    \tableofcontents
    
    \mainmatter                       % arabic again, restarting at 1
    \include{chapters/01-banach}        % plain child: \include forces \clearpage and
                                        % writes chapters/01-banach.aux
    \subfile{chapters/02-hilbert}       % subfiles child: has its own \documentclass
                                        % prologue, so it is read with \subfile
    \include{chapters/03-operators}
    
    \appendix
    \include{appendix/notation}
    
    \backmatter
    \bibliographystyle{plainnat}
    \bibliography{refs}               % with biblatex instead: \printbibliography
    \listoffigures
    \end{document}

    让一章能自己编译:subfiles

    这个需求无处不在,而那个天真的答案——把导言区抄进每一章——一周内就会烂掉。subfiles 宏包改为给子文件一个两行的序幕:主文件仍是一份普通文档,用 \include 或 \subfile 纳入它的子文件,而每个子文件以 \documentclass[../main.tex]{subfiles} 开头,后面接一段正常的 \begin{document}...\end{document} 正文。编译子文件时,它顺着那条路径载入父文档的类和导言区,然后只排这个子文件,于是你得到一份只有单章的 PDF,却带着真实的宏、字体、颜色和定理样式。

    两处机制让它变得可用而不是耍小聪明。其一,当一个 subfile 被单独编译时,\jobname 会变,任何按主文件写的相对路径都会断——宏包正是为此提供 \subfix{},于是图形和文献路径写成 \includegraphics{\subfix{figures/basis}},在两种模式下都能正确解析。其二,向兄弟章节的交叉引用,除非读到兄弟的辅助文件,否则在独立子文件构建里无法解析,这就是 subfile 构建会对本章之外的引用显示 ?? 的原因——那是版式的局限,不是值得追的 bug。

    subfiles 和 subfile 是两个不同的宏包,名字几乎唯一相同。subfile(caption 那一族的一员)更老也更薄:子文件包在类似 \begin{filecontents} 的标记里,再加一个 \endinput 的机关,于是它带着手写的导言区也能单独编译。subfiles 才是复用主导言区的那个,是理智的默认。给图形的另一条路——standalone 类配 \includestandalone——有自己的导言区复用机制(subpreambles=true),只有当一个图真的算一份文档时,才值得为它多装一个包。

    落到实处的决定:一篇学位论文或一本书,如果各章必须能当作独立 PDF 来评审,就用 subfiles 加 \include。一篇论文,如果拆分的唯一理由是可读性,就直接 \input 各节——活动件更少、没有路径的弯弯绕,整份文档永远当一个编。

    % ============================================================
    % chapters/02-hilbert.tex
    % Two ways to use this file:
    %   (a) read by main.tex through \subfile{chapters/02-hilbert}
    %   (b) compiled on its own, with the class and preamble of main.tex
    % ============================================================
    \documentclass[../main.tex]{subfiles}   % path back to the root document
    
    \begin{document}
    \chapter{Hilbert spaces}\label{ch:hilbert}
    
    \section{Definition}
    A complete inner-product space:
    \begin{equation}\label{eq:parallelogram}
      \lVert x + y \rVert^{2} + \lVert x - y \rVert^{2}
        = 2\lVert x \rVert^{2} + 2\lVert y \rVert^{2}.
    \end{equation}
    Cross-references to other chapters keep working in both modes, because the
    auxiliary files of the excluded chapters are still read:
    see \cref{ch:banach} and \cref{eq:projection} on
    \cpageref{eq:projection}.
    
    \begin{figure}[htbp]
      \centering
      \includegraphics[width=.6\textwidth]{\subfix{figures/basis}}  % subfix makes the
      \caption{An orthonormal basis.}\label{fig:basis}               % path work in both modes
    \end{figure}
    
    \end{document}

    路径:import、subimport 和那个挪了位置的文件

    LaTeX 把每个文件名相对主文件(你在命令行里敲的那个)的目录来解析,而不是相对装着该命令的那个文件。这就是「一直好用,直到我把各章放进一个文件夹」这句话存在的全部原因。在 chapters/02.tex 里写 \includegraphics{figures/x},它会去 main.tex 旁边找 ./figures/x,什么也找不到。

    三种修法,按稳健度递增。用 import 宏包显式设路径:\import{chapters/}{02-hilbert}(注意结尾那道斜杠——import 要的是一个目录,不是文件名)让子文件自己的相对路径重新从主文件解析,而 \subimport{sub/}{file} 则相对正在导入的那个文件解析。其二,把图形收在一处、用一个变量索引它们:\graphicspath{{figures/}{chapters/figs/}},不需要包也不换命令。其三,把文件名前缀放进你自己的宏(\newcommand{\figpath}{figures}),处处用 \figpath/name——这是唯一连改名都能活下来的做法。

    另一类麻烦是那个被两个不同主文件读取的文件——论文和学位论文共用的一节,或一个独立编译的章。这里 \subimport 才是对的工具,因为它相对导入它的那个文件解析而非相对根,而带 class=report 式选项的 standalone 类能接手图形那种情形。别用 \input{../shared/x} 加一点侥幸去解决:相对上级路径在你机器上好用,却在 Overleaf 的 zip 里、在 CI 里、在一个文件夹布局差一层的仓库里断掉。

    Master-file tree: which file reads which, and which auxiliary file each kind of inclusion produces ONE ROOT IS COMPILED; EVERYTHING ELSE IS READ BY IT main.tex \jobname = main the only file you hand to the engine \input - transparent splice, no aux preamble/packages.tex preamble/macros.tex \include - clearpage + its own .aux chapters/01-banach.tex chapters/02-hilbert.tex appendix/notation.tex 01-banach.aux 02-hilbert.aux notation.aux labels and citations of that chapter are written here, then pulled back through \@input{...} in main.aux - which is what lets includeonly skip the text main.aux, .toc, .out, .ind A FIGURE THAT IS ITS OWN DOCUMENT figures/circuit.tex standalone class, compiled alone circuit.pdf no page geometry \includegraphics{figures/circuit} or \includestandalone{figures/circuit} paths resolve from the root use \import{dir/}{file} or \graphicspath, \subfix{} for subfiles
    一个主文件、几种子文件:片段用 input 读,章节用 include 读,独立文档当成图形来读。

    把图当作独立文档

    一个 TikZ 或 pgfplots 图,编译开销可能盖过它周围的正文;要止住每次运行都为它买单,办法是单独编它一次、把结果 PDF include 进来。两条路。直白的那条:把 figures/circuit.tex 留作一份完整的 standalone 文档,编成 circuit.pdf,在主文件里 \includegraphics{figures/circuit}——快、可复现,只是图一改你得亲手重编它。自动的那条:主文件里 \usepackage{standalone},然后 \includestandalone[width=.6\linewidth]{figures/circuit},它会在需要时编译子文件并插入,尊重写在子文件类选项里的 border 和 varwidth。

    standalone 类也是对「我插入的图带着一英寸白边」的回答:子文档没有页面几何可继承,所以 \documentclass{standalone} 加 border=2pt 会裁到被画的那个对象,再由 \includegraphics 缩放它。一张坐标图,\documentclass[tikz,border=2pt]{standalone} 加一个 \begin{tikzpicture} 就是最小的可用形状。

    \includestandalone 的代价是实打实的,值得在赶 deadline 前知道:子文件用自己的引擎调用编译,所以一个有 40 张引用图的工程可能比一个大单文件还慢,而且子文件的导言区会在 subpreambles=true 下被载入主文件,当子文件和主文件用不同选项加载同一个包时就会冒出重复定义错误。在一本图改得和正文一样勤的文档里,这是错的工具;在图很稳的地方,它是让一次重建只用几秒的那个。

    % ============================================================
    % figures/circuit.tex — a figure that is a document in its own right
    % compile it alone to get circuit.pdf, or let standalone load the
    % parent preamble with [class=..., mode=packages]
    % ============================================================
    \documentclass[border=2pt,tikz]{standalone}
    
    \usetikzlibrary{circuits.ee.IEC}
    
    \begin{document}
    \begin{tikzpicture}[circuit ee IEC]
      \draw (0,0) to [battery] (0,3) to [resistor] (3,3) -- (3,0) -- (0,0);
    \end{tikzpicture}
    \end{document}
    
    % In the master file, either of:
    %   \includegraphics[width=.5\textwidth]{figures/circuit}   % after compiling it once
    %   \usepackage{standalone}  ...  \includestandalone[width=.5\textwidth]{figures/circuit}

    哪个文件是根,编辑器又是怎么知道的

    在一个多文件工程里,编译器永远只收到一个文件名,其余都是推导出来的:\jobname 就是那个去掉扩展名的名字,辅助文件、目录、索引文件都照它命名。这也解释了为什么在一个用 \include 的工程里直接编子文件,会在子文件旁边生出第二套、更小的一窝辅助文件,把你的清理脚本绕晕。

    编辑器需要你把根声明出来,因为单独打开的一个章文件没有类可拿来编。可移植的惯例是在子文件第一行写一条魔法注释:% !TeX root = ../main.tex,TeXstudio、Kile、VS Code 的 LaTeX Workshop 和 emacs AUCTeX(凭 TeX-default-master-file 或它的自动探测)都认;相关的 % !TeX program = xelatex 注释则钉死引擎。Overleaf 在精神上两条都不无视,但它用一个存起来的「Main document」设置——那是按项目存在服务器上的状态,你把源码下载再传回去就丢了——这也是一个工程从 Overleaf 取回来却拒绝构建的小原因之一。

    要在源码内部按根来分支,得先展开再比较,因为 \jobname 是一个 TeX 字符串寄存器、不是一个宏:\edef\@root{main}\edef\@now{\jobname}\ifx\@root\@now ...\fi 能干这活,而光秃秃的 \ifx\main\jobname 永远为假。同一测试写在一行是 pdfTeX 和 LuaTeX 上的 \ifnum\pdfstrcmp{main}{\jobname}=0。currfile 宏包更舒服地给出同样信息(\currfilename、\currfilepath),而 filehook 宏包允许你在某个具名文件被读取时执行代码,这才是给每章套页眉、或在章边界重置一个计数器的干净路子。

    还有一条关于 \input 语法、在脚本里会咬人的注记:LaTeX 命令形式是带花括号的 \input{file};原始 TeX 原语是带空格、不带花括号的 \input file \relax,它读名字时会吞空格。两种混用,就会冒出那种晦涩的报错——文件名被反引号和引号裹着、引号中间夹着一个空格,而那个多出来的字符正是钻进文件名里的空格。

    一套能撑过一年的布局

    老练的项目最终收敛到的样子,无聊却整齐:一个根文件;一个 preamble/ 目录,放着 \input 片段(宏包、宏、定理样式、列表设置,每个不超过百行);一个 chapters/ 目录,放着被 \include 的单元,编号编到字母序就是文档序;figures/ 摆在它所属的源码旁边,或一个扁平的 figures/ 用子文件夹对应各章名;tables/ 放生成的 .tex 输出;一个 refs.bib;再把投稿场所用的类或样式文件放在根目录,也就是投稿系统会去找的地方。

    两个文件,决定了上面这套布局和一堆乱文件夹之间的差别。.latexmkrc 把引擎、Synctex 开关、文献工具、清理列表钉死,让编辑器、终端和 CI 都按同一方式构建——就是「编译」那一课讲的同一番道理,只是从一份文件挪到一个项目。.gitignore 列出构建产物(*.aux、*.log、*.toc、*.out、*.ind、*.ilg、*.idx?——注意:.idx 是生成的,所以也忽略它,但任何手写的 .bib 要留),再加上 *.synctex.gz,而 *.bbl 只在你投稿的场所不冻结它时才忽略。

    再有一条习惯:移动文件绝不能不编译。一个被改名的目录,是一个能干的项目在晚上十一点猝死最常见的方式,而它吐出的那句日志——LaTeX Error: File `chapters/02-hilbert.tex' not found——正好点名了要改的那个字符串。在提交这次移动之前,先 grep 整个项目里的旧路径;在一套基于 \include 的布局里,路径都住在同一个文件里,而把主根文件保持成「唯一写路径的地方」,正是它的一大优点。

    \mathtt{main.aux} + \sum_{i} \mathtt{ch}i\mathtt{.aux} \;\longrightarrow\; \{\,(\text{key},\ \text{number},\ \text{page})\,\}
    \mathtt{main.aux} + \sum_{i} \mathtt{ch}i\mathtt{.aux} \;\longrightarrow\; \{\,(\text{key},\ \text{number},\ \text{page})\,\}
    上面那张主文件—子文件树图,就是本节描述的布局:一个根、三种子文件、每个子文件一份构建产物。

    本课速查

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

    小节 关键代码
    \text{source read} = \sum_{f \in F} \text{lines}(f), \qquad \text{compile time} \propto \text{source read}
    \documentclass[12pt,a4paper,twoside]{book}
    \documentclass[../main.tex]{subfiles} % path back to the root document
    \documentclass[border=2pt,tikz]{standalone}
    \mathtt{main.aux} + \sum_{i} \mathtt{ch}i\mathtt{.aux} \;\longrightarrow\; \{\,(\text{key},\ \text{number},\ \text{page})\,\}

    常见错误

    • 把 \include 用在一段你本想做拼接的片段上——导言文件、一张表、一个段落。被强制的 \clearpage 会把材料甩到新页,多出来的 .aux 又让下一次局部构建误导人。
    • 把一份在 \includeonly{} 生效状态下构建出来的文档发出去。被排除的章不推进计数器,所以你那章成了「第 1 章」,而伸向被排除文件的每个引用都印上一次完整构建的编号。
    • 在环境里或参数里写 \include{sub/file}。\include 以 \clearpage 开头,那些地方这是非法的;改用 \input 或 \subimport。
    • 把路径相对子文件去解析:chapters/02.tex 里的 \includegraphics{figures/x} 会去 main.tex 旁边找。用 \import{chapters/}{02}、\graphicspath,或者当子文件也要独立编译时用 \subfix{}。
    • 把 \includeonly{}、那一窝 .aux,或子文件的 \documentclass{subfiles} 序幕提交进共享仓库,于是合著者的构建悄悄和你的不一样。
    • 依赖 % !TeX root 注释,而合作者的编辑器根本不认,然后听到「这个章文件编不过」。留一条写进文档的命令行(latexmk -pdf main.tex),不打开任何编辑器也能用。

    关于本课的常见问题

    LaTeX 里 input 和 include 有什么区别?
    \input 是在它出现的精确点上做一次纯文本拼接:不分页、不产生单独的辅助文件,任何地方都能用,包括导言区。\include 会在前后各出一道 \clearpage,把标签和引文写进它自己的 file.aux,并可以用 \includeonly 关掉。章节用 \include,片段用 \input。
    为什么最终构建不该用 includeonly?
    因为被排除的文件从不被读取、它们的计数器从不前进,于是你实际编译的那些材料的编号会变,指向被排除文件的引用则来自上一次运行过期的 .aux。数字可以看着合理却是错的。在分享或提交之前永远先做一次完整构建。
    怎么编译一本书里的单独一章?
    要么在主文件里写 \includeonly{chapters/ch02} 然后编译主文件,要么把那一章做成一个 subfiles 文档,以 \documentclass[../main.tex]{subfiles} 开头并自带 \begin{document}。前者更快、保持一套构建;后者给出该章一份带着真实导言区的独立 PDF,且图形路径需要 \subfix{}。
    我 include 进来的文件找不到它的图片,为什么?
    因为 LaTeX 相对主文件解析文件名,不相对装着那条命令的文件。可选办法:加载 import 宏包并写 \import{chapters/}{file},用 \graphicspath{{figures/}{chapters/figs/}} 一次性声明额外的目录,或者用 subfiles 时把路径包进 \subfix{}。
    能在 \include 里面再套 \include 吗?
    技术上这条命令是允许的,但语义没用:只有最外层的 \include 会得到 \clearpage 处理和辅助文件重定向,而 \includeonly 不会选中里面那个。要套,就在被 include 的章里套 \input,它透明、自身不保存任何状态。
    图应当拆成单独的 .tex 文件吗?
    如果它们既费编译又稳定,是的:每个都当作一个 standalone 类文档,编成 PDF 再 \includegraphics 结果,或者用 standalone 宏包配 \includestandalone 把它自动化。如果你在写的同时图一直在变,就用 \input 把绘图代码直接纳进来——\includestandalone 每次运行都会重编子文件,可能比一个单文件还慢。

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

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

    KaTeX 错误
    试一个例子

    继续读

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