3

I stumbled along a strange effect. Consider the following example of two columns of numbers:

\documentclass{article}

\usepackage{xcolor}
\usepackage{tikz}
\usepackage{multicol}
\usepackage{listings}

\begin{document}

\begin{multicols}{2}
\begin{lstlisting}[basicstyle=\tiny]
1
2
3
4
\end{lstlisting}
\end{multicols}

\end{document}

I expect this to produce two columns with the same number of rows. The first should contain 1 and 2, the second should contain 3 and 4. Unfortunately, I got the following unbalanced columns: image of the error This error only occurs when either the xcolor or tikz package is loaded, and only when the basicstyle of lstlisting is set to either \tiny or \scriptsize. I have absolutely no clue why this is happening.

Why does this happen and how can I solve it?

4

hmm, tricky. lstlisting adds aboveskip and belowskip before and after the environment (and by default they are about 6pt). Now since the listing starts as the first item in the multicol, the aboveskip is dropped as all vertical space is dropped at the very beginning. But the belowskip remains which means that we do not have 4 lines but more or less 5 (and the last one some empty white space).

so one way to fix that is to set

  \begin{lstlisting}[basicstyle=\tiny,belowskip=0pt]

The use of multicols=2 works for the same reason, because now the skips are added outside of multicol not inside.

I should probably add that multicolsnormally also removes vartical space at the end of the last column to ensure that balancing works well. However, the belowskip space added by lstlisting is actually hidden as it is followed by a) an additional skip of 0pt and b) a color change, i.e., what we have there is

.\penalty -50
.\glue 6.0 plus 2.0 minus 2.0      % <-- that's belowskip
.\glue 0.0
.\pdfcolorstack 0 pop

so multicol has no chance to remove it. I think this could be considered a bug in listings as such spaces should be accessible from the outside, e.g., it should be able to interact with \addvspace which is also not possible due to the colorstack command.

Perhaps this should be brought to the attention of the the listings maintainer(s).

4

When the multicol package is loaded, it can be used to typeset multi-column listings. These are specified with the multicols key:

\documentclass{article}
\usepackage{xcolor}
\usepackage{tikz}
\usepackage{multicol}
\usepackage{listings}
\begin{document}
\begin{lstlisting}[multicols=2,basicstyle=\tiny]
1
2
3
4
\end{lstlisting}
\end{document}
  • Thanks! That indeed solves the problem. My first question remains: why does this happen? – Safron Nov 26 '17 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.