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

packagestikz-pgf

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?

Best Answer

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
\AddToHook{begindocument/before}{%
  \@ifpackageloaded{tikz}{\usetikzlibrary{tikzmark}}{}%
}
\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
\@ifundefined{AddToHook}{%
    \RequirePackage{etoolbox}%
    \AtEndPreamble{%
      \@ifpackageloaded{tikz}{\usetikzlibrary{tikzmark}}{}%
    }%
  }{%
    \AddToHook{begindocument/before}{%
      \@ifpackageloaded{tikz}{\usetikzlibrary{tikzmark}}{}%
  }%
}
\makeatother

\usepackage{tikz}

\begin{document}

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

\end{document}