[Tex/LaTex] Wrong line spacing and indents in multicol environment

multicol

I am producing an answersheet using LaTeX. I want to control the number of columns and I use the multicol package for that. To force columnbreak I also use \columnbreak command.

I face these problems

  1. The first line in each column always indents bad.
  2. The spacing between the first line and second line of each column is bad.
  3. There is too much vertical space below each column.
  4. I would also like to align the numbers [1], [2], etc as right justified.

Any help would be appreciated.

This is my MWE.

\documentclass{article}
\usepackage{multicol,pgf,pgffor,calculator,ifthen}
\setlength{\columnseprule}{0.4pt}
\newcommand{\AuxAnswerspace}[2]{
    \DIVIDE{#2}{#1}{\Auxlinesx}
    \FLOOR{\Auxlinesx}{\Auxlinesx}
    \foreach\x in {1,...,#2} {
        \MODULO{\x}{\Auxlinesx}{\Auxstartx}
        \ifthenelse{\equal{\Auxstartx}{1}}{}{\vspace{.07cm}}
        \noindent[\textbf{\x}] \hfill\newline
        \ifthenelse{\equal{\Auxstartx}{0}}{\vfill\null\columnbreak}{\vspace{.07cm}}
    }
}

\newcommand{\answerspace}[2]{
    \hrule
    \begin{multicols}{#1}
        \noindent\AuxAnswerspace{#1}{#2}
    \end{multicols}
    \hrule
}
\begin{document}
    \section*{Part-I}
    \answerspace{3}{15}
    \vspace{.3cm}
    Correct = \hfill Wrong = \hfill Marks = \hspace{3cm}
    \vspace{.3cm}
    \hrule
\end{document}

enter image description here

Best Answer

The code below, I think, answers all of your issues. It produces:

enter image description here

As has already been pointed out the lines that didn't end with a % were causing issues. Apart from this, you are putting \newlines at the end of every line, including those that appear just before a \columnbreak, and this causes havoc with the line spacing. As you are already loading the pgf package, I suggest using it for the calculations. I'm also not a fan of ifthenelse constructs so instead I use \ifnum...\fi because I find this much clearer and cleaner.

Here is the full code:

\documentclass{article}
\usepackage{multicol,pgf,pgffor}
\setlength{\columnseprule}{0.4pt}
\newcommand{\AuxAnswerspace}[2]{%
    \pgfmathsetmacro\Auxlines{int(ceil(#2/#1))}%
    \foreach \x [evaluate=\x as \line using {int(mod(\x,\Auxlines))}] in {1,...,#2} {%
        \hspace*{2em}\llap{[\textbf{\x}]}%
        \ifnum\line=0\vfill\columnbreak\else\newline\fi%
    }%
}
\parindent=0pt

\newcommand{\answerspace}[2]{%
    \hrule%
    \begin{multicols}{#1}%
        \AuxAnswerspace{#1}{#2}%
    \end{multicols}%
    \hrule%
}
\begin{document}
    \section*{Part-I}
    \answerspace{3}{15}
    \vspace{.3cm}
    Correct = \hfill Wrong = \hfill Marks = \hspace{3cm}
    \vspace{.3cm}
    \hrule
\end{document}

Finally, to right justify the numbers I have used \hspace*{2em}\llap{[\textbf{\x}]. This inserts 2em width of space and then \llap{...} writes stuff to the left without moving the "cursor" position.

Related Question