The best way to draw an arbitrary number of lines in LaTeX

diagramsmultidotikz-pgf

I wish to produce a number of sections, each followed by a number of lines i. This is how I have done it using multido to repeat a custom command \drawline i times.

\documentclass[12pt]{memoir}

\usepackage{tikz}
\usepackage{multido}

\newcommand{\drawline}{%
        \begin{tikzpicture}%
            \draw [gray] (0,0) -- (\textwidth, 0);%
            \node [above right] at (0,0) {\i.};
        \end{tikzpicture}%
        \\%
}


\begin{document}

\section*{Section 1}    
\multido{\i=1+1}{5}{\drawline}


\section*{Section 2}
\multido{\i=1+1}{4}{\drawline}
    
\end{document}

Which produces this:

enter image description here

The problem I am having seems to be related to the breakline \\ following the tikzpicture definition. I need to break lines between calls of \drawline so that the lines show up in sequence and not next to each other. However, I have two issues:

  1. I get an extra unnecessary empty line after the last call of \drawline, meaning extra space between sections.
  2. When the lines of one section fill a page more or less perfectly, the next section appears on the following page, but not at the top of the page. There is whitespace between the top of the page and the section title.

The syntax for multido is this according to the documentation:

\multido{*variables*}{*repetitions*}{*stuff*}

Is there a way to reference repetitions as a variable? For instance, if one wanted the line break to apply for all n where n < repetitions? In that case, a conditional could be used to break line in all cases but the last one.

Or, can one instead use coordinates in tikzpicture relative to another tikzpicture? This way \drawline could be defined without recourse to the \\ at the end.

Best Answer

It is not necessary to use multido when tikz is loaded. Just use \foreach:

enter image description here

\documentclass[12pt]{memoir}

\usepackage{tikz}

\newcommand{\linespace}{6mm}
\newcommand{\drawlines}[1]{\tikz{\foreach \n in {1,...,#1}
    {\draw[gray](0,-\n*\linespace)node[above right,black]{\n.}--(\textwidth,-\n*\linespace);}}}

\begin{document}

\section*{Section 1}    
\drawlines{5}

\section*{Section 2}
\drawlines{4}
    
\end{document}