TransWikia.com

Getting needspace to work in multicols

TeX - LaTeX Asked on August 16, 2021

I have code that generates multiple lists of data in the form of XeLaTeX source. Because the lines of data are very short, I’m presenting it in a multicols environment. Each list has a few headings in it. Occasionally the list of data is very short – just a single heading and one line of data – and in this case, I’m struggling to prevent the heading and following line from being split across columns. Here’s a MWE showing the problem and my attempt to fix it using needspace:

documentclass[a4paper]{article}
usepackage{multicol}
usepackage{needspace}
newcommand{tblheading}[1]{needspace{2baselineskip}textbf{#1}newline}
begin{document}
begin{multicols}{3}
tblheading{Heading}
Entry
end{multicols}
end{document}

I’ve tried using Needspace* instead of needspace, I’ve also tried adding raggedcolumns, increasing the requested space from 2baselineskip, and using par, or * instead of newline, but whatever I try, I cannot prevent these two lines from being split between two columns. Can anyone help?

(I know that in principle I could use a minipage or perhaps samepage environment, but I don’t think that’s possible here because I really need to keep the special handling within the tblheading macro due to the way the data is generated.)

2 Answers

The minisec command of KOMA does more or less this:

documentclass[a4paper]{article}
usepackage{multicol}
makeatletter
newcommandminisec[1]{%
    if@noskipsec leavevmode fi
    par
    @afterindentfalse
    if@nobreak
      everypar{}%
    else
      addpenalty@secpenaltyaddvspace{1.5ex}% space before, adjust if needed
    fi
  {parindent z@
   setlength{parfillskip}{z@ plus 1fil}
    normalfontbfseries
    nobreakinterlinepenalty @M #1parnobreak%
  }nobreak
  @afterheading
}                              
makeatother
begin{document}
begin{multicols}{3}
minisec{Heading}
Entry
end{multicols}
end{document}

Answered by Ulrike Fischer on August 16, 2021

Multicol actually formats the entire page as a single column, then splits it into two or more equal lengths. It turns out that @afterheading will not prevent this split from taking place, so subsection* etc won't work either. My old version of needspace will work, fortunately.

documentclass[a4paper]{article}
usepackage{multicol}
setlengthcolumnseprule{.4pt}
usepackage{lipsum}

makeatletter
newcommand{tblheading}[1]{parrule{0pt}{dimexpr 2baselineskip-dpstrutbox}vspace{-2baselineskip}newline
  indenttextbf{#1}newline}
makeatother

begin{document}
begin{multicols}{3}
noindentrule{columnwidth}{49baselineskip}% 48 will go in first column

tblheading{Heading}
Entry

lipsum[1-4]
end{multicols}
end{document}

Answered by John Kormylo on August 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP