# \AtBeginDocument + \usetikzlibrary + remember picture = undefined \savepicturepage

I'm writing a package that first checks whether the tikz package is loaded, then add some tikz libraries

However, this package has a conflict with "remember picture, overlay" option of tikzpicture

My MWE that embeds the content of the package into a single tex file:

\documentclass[10pt,a4paper]{article}

\AtBeginDocument{\usetikzlibrary{tikzmark}}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[remember picture, overlay]
\draw (0,0) -- (1,1);
\end{tikzpicture}

\end{document}


In Texmaker (I don't know if it matters), this can generate the pdf file at the initial build. However, if I build the .tex file one more time, it gives an error message: "Undefined control sequence. \savepicturepage"

(cf. \usetiklibarary part is inside the package and should come before \usepackage{tikz}, and that's why I use \AtBeginDocument. For another reason, I should also use [remember picture, overlay] option)

Anyone knows why?

• you can't load the library there, this is too late. With a current latex you can use another hook: \AddToHook{env/document/before}{\usetikzlibrary{tikzmark}} Nov 3, 2021 at 21:55
• Without "remember picture, overlay" part, it seems okay to load the library there though Nov 3, 2021 at 22:57
• loading perhaps. But did you try to use it? Add a \tikzmark{blub} and you will get the same error. tikzmark uses the aux-file and so must be loaded before this file is processed. Nov 3, 2021 at 23:12
• Oh I see. I indeed cannot use it... Nov 3, 2021 at 23:26

You can't generally load TikZ libraries at begin document.

With a current LaTeX you can do the loading just before begin document:

documentclass[10pt,a4paper]{article}

\makeatletter % this will go in the .sty file
}
\makeatother

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[remember picture, overlay]
\draw (0,0) -- (1,1);
\end{tikzpicture}

\end{document}


If you want this to work also with older versions of LaTeX, you need to load etoolbox and to use \AtEndPreamble.

\documentclass[10pt,a4paper]{article}

\makeatletter % this will go in the .sty file
\RequirePackage{etoolbox}%
\AtEndPreamble{%
}%
}{%
}%
}
\makeatother

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}[remember picture, overlay]
\draw (0,0) -- (1,1);
\end{tikzpicture}

\end{document}

• Thanks! I'm still using older versions, so etoolbox may be the only option. One final question: doesn't etoolbox make my build slow? I tend to be a little bit worried about using a multi-function package that might slow down my build. Nov 4, 2021 at 13:51
• @user182849 I see no reason to worry. Nov 4, 2021 at 14:09