[Tex/LaTex] Combination of Subfiles, Apacite and Babel packages result in LaTeX error

apa-stylebabelbibtexsubfiles

For my bachelor thesis, I want to write my chapters in separate files and be able to compile them separately. To combine them, I use the subfiles package. For citations, I have to use Apa style via the apacite package.

As already discussed in Use of apacite package with subfiles package or standalone package results in LaTeX Error: Can be used only in preamble, apacite and subfiles don't go together well. To fix this problem I use the solution as posted:

\usepackage{etoolbox}
\makeatletter
\patchcmd{\nocite}{\ifx\@onlypreamble\document}{\iftrue}{}{}
\makeatother

This works fine, but I want my reference list to be in English (not in French as is standard with apacite). Normally, I use the babel package to correct this problem, but with the subfiles package this results in the following error:

! LaTeX Error: Can be used only in preamble.
l.4 \cite{test}

Does anyone know how to fix this?

The code I used:

main.tex

\documentclass{article}
\usepackage{subfiles}
\usepackage{apacite}
\usepackage[english]{babel} % works fine without babel
\usepackage{etoolbox}
\makeatletter
\patchcmd{\nocite}{\ifx\@onlypreamble\document}{\iftrue}{}{}
\makeatother

\begin{document}
\subfile{chapter1}

% Bibliography:
\newpage
\bibliographystyle{apacite} 
\bibliography{../ref/references} 

\end{document}

chapter1.tex:

\documentclass[./main.tex]{subfiles}
\begin{document}
text
\cite{test}
\end{document}

Best Answer

Setting \errorcontextlines=\maxdimen helps to reveal what's going on.

babel saves the old definition of \nocite in \org@nocite, so either:

  1. Patch \nocite before loading babel, or
  2. Patch \org@nocite as well, after loading babel.

The first is probably the better solution:

\documentclass{article}
\errorcontextlines=\maxdimen
\usepackage{subfiles}
\usepackage{etoolbox}
\usepackage{apacite}
\makeatletter
\patchcmd{\nocite}{\ifx\@onlypreamble\document}{\iftrue}{}{}
\makeatother
\usepackage[english]{babel} % works fine without babel

\begin{document}
\subfile{94989-chapter1}

% Bibliography:
\newpage
\bibliographystyle{apacite} 
\bibliography{../ref/references} 

\end{document}