[Tex/LaTex] TikZ grid and remember picture, overlay

tikz-pgf

In A package to help with layout generation? Graph paper in the background? the question was asked in the comments as to why it was necessary to shift the whole picture in order to line up the grid properly. It never had a satisfactory answer.

Unfortunately, it appears that the position as well as the grid generation routine are influenced by the paragraph indentation.

Consider the MWE below and run it with both commented as well as un-commented lines.

\documentclass{article}
\usepackage{tikz}
\begin{document}
%\null
%\noindent
\begin{tikzpicture}[remember picture, overlay]
     \draw[line width=1pt,color=teal,step=1cm] (current page.south west) grid ++(5cm,5cm);
  \end{tikzpicture}
XXXX
\end{document}

This produces the following:

enter image description here

If you un-comment the lines you get a different layout. If you add a shift of 7.8mm it results in integral squares

\draw[line width=1pt,color=teal,step=1cm,xshift=-7.8mm,yshift=-7.8mm] (current page.south west) grid ++(5cm,5cm);

What is the right way to compensate and why does the algorithm does not produce integral squares? How can I enforce integral squares?

Best Answer

I guess the trick is to shift the grid slightly. The required shift is defined in the .aux file, which defines a point called pgfid<x>, where <x> is refers to the index of the tikzpicture. In general, this number is given by \pgfpictureid. The following code seems to work (after compiling twice) for all pages.

\documentclass{article}
\usepackage{tikz}
\usepackage{lipsum}

\begin{document}

\newlength\shiftx
\newlength\shifty

\makeatletter
\newcommand\calcshift{%
   \pgfsys@getposition{\pgfpictureid}\@basepoint%
   \pgf@process{\pgfpointorigin\@basepoint}%
   \setlength\shiftx\pgf@x%
   \setlength\shifty\pgf@y%
}
\makeatother

\begin{tikzpicture}[remember picture, overlay]
    \calcshift
    \draw [line width=1pt,color=teal,step=1cm,xshift=-\shiftx, yshift=-\shifty] 
         (current page.south west) grid ++(5cm,5cm);
\end{tikzpicture}

\lipsum{4}

% --- just some other tikz picture
\begin{tikzpicture}
  \draw (0, 0) rectangle (1, 1);
\end{tikzpicture}

\begin{tikzpicture}[remember picture, overlay]
    \calcshift
    \draw [line width=1pt,color=teal,step=1cm,xshift=-\shiftx, yshift=-\shifty] 
         (current page.south west) grid ++(5cm,5cm);
\end{tikzpicture}

\end{document}