# todonotes breaks pgfplots and tikz spy with externalization

I want to use todonotes in a document that also uses pgfplots, tikz spy and tikz external. Unfortunately, todonotes breaks the layout of pgfplots figures as illustrated by the following example:

\documentclass{article}
\usepackage{tikz}
\usepackage{todonotes}
\usepackage{pgfplots}
\usepackage{lipsum}
\usepackage{xpatch}

\usetikzlibrary{external}
\usetikzlibrary{spy}

\tikzexternalize
[
mode=list and make,
% Does not help
optimize command away={\todo}{1},
]

% Disable externalization for \todo in order to avoid compilation errors.
\xpretocmd\todo{%
\bgroup\tikzexternaldisable
}{}{}

\xapptocmd\todo{%
\egroup
}{}{}

\begin{document}

\begin{figure}[tb]
\centering
\begin{tikzpicture}
[
spy using outlines={%
connect spies,
rectangle,
}
]
\begin{axis}
[
xmin=0,xmax=320,
ymin=0,ymax=300,
]

\coordinate (spyat) at (292,223);
\coordinate (magat) at (150,90);
\end{axis}

\spy[thick] on (spyat) in node at (magat);
\end{tikzpicture}
\end{figure}

% Adding todo does not work
\lipsum\todo{foo}\lipsum
% Works!
%\lipsum\lipsum

\end{document}


This is how the figure looks like:

And this is how the figure supposed to look:

One way to avoid the broken layout is either not to use todonotes or to disable externalization altogether. The latter is however not an option.

Is there any other way to overcome the problem?

Answering my own question. \pgfsyspdfmark written to the .aux file seems to be responsible for the broken layout. Hence, disabling its usage in externalized documents as follows

\ifthenelse{\equal{\tikzexternalrealjob}{\pgfactualjobname}}{}{%
\renewcommand\pgfsyspdfmark[3]{}%
}


solves the problem. This check requires the ifthen package.

Alternatively, one can use the \tikzifexternalizing command, as suggested in the comments by Max Snippe:

\tikzifexternalizing{%
\renewcommand\pgfsyspdfmark[3]{}%
}{}

• You could probably also use \tikzifexternalizing{<true code>}{<false code>}. – Max Jul 22 '18 at 8:44
• True, this seems to work as well. – caustic Jul 22 '18 at 9:45