1

I want to automate some things in LaTeX using loops and saveboxes, but the boxes don't want to go automatically to the next line when there is no space for them (saveboxes are necessary). The code below is a simple example of what I'm trying to achieve (boxes are not created via loop, but I'm making it this way for the purpose of a simple demonstration). X will be some text

\usepackage{xsavebox}
\usepackage{pgffor}
\foreach \n in {3,...,11}{\xsbox{R.1.\n}{\textbf{R.1.\n}~X\hspace{2em}}}
...
\foreach \n in {3,...,11}{\xusebox{R.1.\n}}

This code results in something like this: enter image description here

1
  • Do you have any space between the boxes, that allow line breaks? If you have something like cfhtzgsrz, LaTeX can't break it, except you add a hiphenation rule. You could try adding \mbox{}\- before every box. That should allow line break. I can't check on the phone. Beside the fact, that people like David and egreg will tell me, that this is a less correct solution. May 10, 2022 at 6:06

1 Answer 1

2

You need to use \global before \setbox, because \foreach from pgf does each loop-step in a group. The local setting is forgotten when the group is leaved. And you want to use \penalty0 in order to allow a breaking point, because each \xsbox exectes \leavevmode before putting box, so you are in horizontal mode.

\foreach \n in {3,...,11}
    {\global\setbox\n=\hbox{\textbf{R.1.\n}~X\hskip2em}%
     \leavevmode\copy\n\hfil\penalty0 }
...
\foreach \n in {3,...,11}{\leavevmode\box\n\hfil\penalty0 }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .