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

\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

  • 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 at 6:06

1 Answer 1


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}
     \leavevmode\copy\n\hfil\penalty0 }
\foreach \n in {3,...,11}{\leavevmode\box\n\hfil\penalty0 }

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.