LaTeX 加载子文件夹中的文档

我们在编写大型 LaTeX\LaTeX 文档的时候,为了方便组织文档的结构,通常需要讲整个文档拆成若干个 .tex 文件,然后在主文件中使用 \include 命令来加载这些文档。

为了保持根文件夹的干净,通常我会将这些文件放在若干个子文件夹中。这样在本地编译的时候,没有发现任何问题(我使用的是 VS Code + LaTeX Workshop,配置了 latexmk),但是当我进行远程编译测试的时候,却发现始终无法通过。

关于这个问题,网上众说纷纭,不过大致可以确定是写入权限的问题。在 LaTeX won’t include from other directories | The TeX FAQ 中,其中明确指出对于 LaTeX\LaTeX 对于父文件夹是没有写入权限的,但根据其中的描述,对于子文件夹,应该是没有问题的,这和我遇到的情况不符。

最终,我在 Common Mistakes that cause Automated Processing to Fail | arXiv e-print repository 中找到了和我一样的问题,在里面它明确提到,在它的编译设置下,使用 \include 加载子文件夹中的文件会报错,并给出了明确的例子:

1
2
3
4
5
\input{file}           %OK, does not create separate .aux file
\input{subdir/file} %OK, does not create separate .aux file

\include{file} %OK because file.aux can be written
\include{subdir/file} %WILL FAIL fail because sub/file.aux cannot be written

当我把 \include 改成 \input 之后,编译的确通过了,但是这并不能完全解决我的问题,因为我平时需要用到 \includeonly 功能,\include 命令对我来说时不可替代的。

为了找到问题的所在,接下来对我几种不同的编译设置进行了测试。

测试文件:

main.tex
1
2
3
4
5
6
7
\documentclass{article}

\begin{document}

\include{chaps/a}

\end{document}
chaps/a.tex
1
aaa

测试结果如下:

  • 使用 latexmk -xelatex -interaction=nonstopmode -file-line-error main.tex 编译,成功;
  • 使用 latexmk -xelatex -interaction=nonstopmode -output-directory=out main.tex 编译,成功(如果有其它错误也不会报错,但无法生成 pdf 文件);
  • (默认设置)使用 latexmk -xelatex -interaction=nonstopmode -file-line-error -output-directory=out main.tex 编译,失败;
  • 手动创建 out/chaps 文件夹之后,使用 latexmk -xelatex -interaction=nonstopmode -file-line-error -output-directory=out main.tex 编译,成功。

可以看出,自动编译失败的主要原因是,在第一遍编译的时候,可以创建 out 文件夹,但是无法创建 out/chaps 这个子文件夹,但是第二遍编译的时候就可以了。这应该是一个 bug 吧。

而在本地使用 LaTeX Workshop 编译时,应该是打上了补丁,就像我上面第4个测试一样,提前创建了文件夹,因此编译可以正常通过。

因此,最终的解决方法是,继续使用 \include,在远程测试的时候,提前创建好所需的文件夹就可以了。