`chapterbib`を`subfile`と同時に使う
ChenZhijin
.com

`chapterbib`を`subfile`と同時に使う

chapterbibsubfileと同時に使う

LaTeXsubfileを使う

subfileは長いLaTeXファイルを分割して、それぞれコンパイルできる。 例えば、今博士論文を書いていて、章ごとにファイルを作り、コンパイルしたいである。

main.texに:

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}

LaTeXchapterbibを使う

chapterbibは章ごとに引用を作るのに使われる。しかし、chapterbibを使うと、includeで各章の内容のmainのファイルに入れる:

main.texでは:

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

さらに、全ての章のファイルは文章のbody部分のみが許され、\begin{document}\end{document}さえ書けない:

各章のファイルchapter1.tex

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

よって、章ごとのファイルはコンパイルできない。手動で切り替えするのは大変手間がかかる。

ここで、LaTeXのmacroの強さが出てくる:

LaTeXchapterbibsubfileと同時に使う

まず、main.texのbodyにmacroを作り、mainファイルからコンパイルしているフラグとして使う。そして、subfileincludeに変える:

1
2
3
4
5
6
7
% main.tex
\usepackage{subfiles}
\begin{document}
\newcommand*{\BuildingFromMainFile}{} % mainファイルからコンパイルしているフラグ
\subfile{chapter1}
\subfile{chapter2}
\end{document}

次に、各章の最初に、フラグが定義されているかどうかをチェックする。 定義されていない場合は、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

これで完了です!

タグ: