同时使用`chapterbib`及`subfile`
ChenZhijin
.com

同时使用`chapterbib`及`subfile`

同时使用chapterbibsubfile

LaTeX中使用subfile

使用LaTeX的subfile包可以方便地将一个大型LaTeX工程分割成独立文件。例如我在写博士论文时将各个章节分割成单个文件,这样每次预览时就只需要编译单个章节。

例如,在主tex文件main.tex中添加chapter1chapter2等章节文件:

1
2
3
4
5
6
% main.tex
\usepackage{subfiles}
\begin{document}
\subfile{chapter1}
\subfile{chapter2}
\end{document}

章节的文件chapter1.tex

1
2
3
4
5
6
7
% chapter1.tex
\documentclass[main.tex]{subfiles}
\begin{document}
\chapter{A Good Chapter}
Hello world.
\bibliography{references}
\end{document}

之后按照通常情况编辑每个章节的内容即可。 每个章节的tex文件都可以单独编译,最后编译main.tex就可以输出整个文件。

LaTeX中使用chapterbib

chapterbib非常适合用来自定义引用,包括直接给每个章节添加独立的参考文献列表。许多大学的论文格式(包括硕士论文和博士论文)都要求每个章节都有独立的参考文献。

chapterbib的机能所限,需要在main.tex中使用include来添加章节内容:

main.tex中:

1
2
3
4
5
6
% main.tex
\usepackage{subfiles}
\begin{document}
\include{chapter1}
\include{chapter2}
\end{document}

同时,每个章节的文件都只能有文件本体(不包括preamble),甚至不能包含\begin{document}\end{document}

例如,在章节文件chapter1.tex中:

1
2
3
4
% chapter1.tex
\chapter{A Good Chapter}
Hello world.
\bibliography{references}

所以要同时使用chapterbibsubfile,不得不在两个版本之间切换,十分痛苦。

这时宏的强大之处就体现出来了:

LaTeX中同时使用chapterbibsubfile

首先,在main.tex的document中定义一个宏\BuildingFromMainFile,用来标记是从main.tex编译的,然后将subfile改为include

1
2
3
4
5
6
7
% main.tex
\usepackage{subfiles}
\begin{document}
\newcommand*{\BuildingFromMainFile}{}
\subfile{chapter1}
\subfile{chapter2}
\end{document}

下一步,在章节文件中检查是否定义了上述宏\BuildingFromMainFile。 如果没有定义的话,说明是从章节文件编译的,那么会自动添加preamble:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
% beginning of chapter1.tex

\ifdefined\BuildingFromMainFile
\else
\documentclass[main.tex]{subfiles}
\begin{document}
\fi

\chapter{A Good Chapter}
Hello world.

\bibliography{references}

\ifdefined\BuildingFromMainFile
\else
\end{document}
\fi

完工。

标签: