% Copyright 2012 Heiko Oberdiek (see http://tex.stackexchange.com/a/70108)
% Copyright 2013 Patrick Gundlach (colorization and package creation)
% Copyright 2013 Dominik Wagenfuehr (line counter and baseskip)
% Lizenz: http://creativecommons.org/licenses/by-sa/3.0/

\ProvidesPackage{graphpaper}

\RequirePackage{atbegshi}
\RequirePackage{picture}
\RequirePackage{xcolor}

\newcounter{graphpapercounter}

\AtBeginShipout{%
  \AtBeginShipoutUpperLeft{%
    \color{lightgray}%
    \setcounter{graphpapercounter}{1}%
    \put(\dimexpr
      \ifodd\value{page}\oddsidemargin\else\evensidemargin\fi + 1in\relax,
      -\dimexpr\topmargin + 1in + \headheight + \headsep\relax){%
      \begin{picture}(0,0)%
        % the normalsize is necessary because at the begin of the page
        % the font size could be smaller and so we would have a wrong
        % unitlength.
        \normalsize% 
        \setlength{\unitlength}{\baselineskip}%
        % dimen0 is the position of first rule
        \setlength{\dimen0}{\topskip}%
        \@whiledim\dimen0<\dimexpr\textheight+\baselineskip+1sp\relax\do{%
          \put(0,-\dimen0){\line(1,0){\textwidth}}%
          % show line counter
          \put(-18px,-\dimen0+0.1\baselineskip){\small{}\thegraphpapercounter}%
          \addtolength{\dimen0}{\unitlength}%
          \addtocounter{graphpapercounter}{1}%
        }%
      \end{picture}%
    }%
  }%
}
