1

I have a document involving multiple colorboxes containing 1-3 words each in a single line, separated by ,. Imagine typesetting a couple of boxes in a line, so that there's only 3cm of space to the right margin of the document. But the next box is e.g. 5cm wide.

I want this box to be set on the next line, since it would not fit into the current line anymore. Instead, it gets typeset in that same row and overflows the right margin by 2cm. Sometimes, with longer boxes, they don't just overflow the right margin but also the paper. Only if the previous box already overflows the right margin, a linebreak gets inserted.

How can I tell LaTeX to insert a line break before that next box if it would not fit into the current line anymore? And not just if the previous box also didn't fit? I have searched the net but could not find anything. All answers I found so far deal with multi-line text within the boxes, which is not the problem in my case. I need multiple single-line boxes being typeset over multiple lines. I can't imagine that LaTeX is not capable of such a simple thing! Thanks in advance :)

3

Use the \filbreak trick (The TeXbook, page 111), but with horizontal glue (see also https://tex.stackexchange.com/a/72787/4427).

\documentclass{article}
\usepackage{showframe} % just for showing the margins

\newcommand{\mybox}[1]{%
  \hfil\penalty0\hfilneg
  \fbox{#1}%
}
\newenvironment{awkwardpar}
 {\par\linepenalty=5000 }
 {\par}

\begin{document}

\begin{awkwardpar}
Some word \mybox{some word} xyz \mybox{some word again} 
and \mybox{some} Some word \mybox{some word}
other words \mybox{some word again}
Some word \mybox{some} other words \mybox{some word again}
Some word \mybox{some word}
other words \mybox{some word again} Some word \mybox{some word}
xyz \mybox{some word again} and \mybox{some}
other words \mybox{some word again} Some word \mybox{some word}
other words \mybox{some word again}
\end{awkwardpar}

\end{document}

enter image description here

More simply: use \raggedright (or flushright for the environment form).

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.