# Wrong marginnote positions inside a tikzpicture with XeLaTeX

The marginnote package offers the \marginnote macro. I use this inside a tikzpicture environment to place notes into the margin.

While this works without problems when compiling with pdfLaTeX, this gives horizontal shifts when compiling with XeLaTeX.

Consider the following MWE:

\documentclass{article}
\usepackage{marginnote}
\usepackage{tikz}
\usepackage[showframe]{geometry}

\begin{document}

This line\marginnote{ABC} contains a margin note.

\begin{tikzpicture}
\fill[red] (-1,-1) rectangle (1,1);
\node[right] at (1,0) {This line\marginnote{ABC} contains a margin note.};
\end{tikzpicture}

\end{document}


Compilation (twice) with pdfLaTeX (using MiKTeX on Windows) gives the expected result:

Compilation with XeLaTeX (using MiKTeX on Windows) gives shifts the second note inside the tikzpicture:

Can this code be modified to compile correctly for pdfLaTeX and XeLaTeX?

Again, the solution from here, which is simply copying the definition from pgfsys-common-pdf-via-dvi.def.

% !TEX program = XeLaTeX

\documentclass{article}
\usepackage{marginnote}
\usepackage{tikz}
\usepackage[showframe]{geometry}

\begin{document}

\makeatletter
\def\pgfsys@hboxsynced#1{%
{%
\pgfsys@beginscope%
\setbox\pgf@hbox=\hbox{%
\hskip\pgf@pt@x%
\raise\pgf@pt@y\hbox{%
\pgf@pt@x=0pt%
\pgf@pt@y=0pt%
\special{pdf: content q}%
\pgflowlevelsynccm%
\pgfsys@invoke{q -1 0 0 -1 0 0 cm}%
\special{pdf: content -1 0 0 -1 0 0 cm q}% translate to original coordinate system
\pgfsys@invoke{0 J [] 0 d}% reset line cap and dash
\wd#1=0pt%
\ht#1=0pt%
\dp#1=0pt%
\box#1%
\pgfsys@invoke{n Q Q Q}%
}%
\hss%
}%
\wd\pgf@hbox=0pt%
\ht\pgf@hbox=0pt%
\dp\pgf@hbox=0pt%
\pgfsys@hbox\pgf@hbox%
\pgfsys@endscope%
}%
}
\makeatother

This line\marginnote{ABC} contains a margin note.

\begin{tikzpicture}
\fill[red] (-1,-1) rectangle (1,1);
\node[right] at (1,0) {This line\marginnote{ABC} contains a margin note.};
\end{tikzpicture}

\end{document}


The result is the same as your first picture.

I did not raise the duplicate-vote because the last one I do so, someone doubt that it is the case.

• Thank you for providing this helpful answer. The linked question (which is one year younger than mine) has several answers also containing further links which clouded the solution for me ... So, it's good to have an answer on this place :-) – Thomas F. Sturm Apr 24 '17 at 15:17