[Tex/LaTex] Iterate over space-separated list


I’ll briefly explain the background in case this can be solved simpler but I’d still be interested in an answer to the actual question, too.

My chapter titles are very narrow and use a large font so that it may happen that it has to be broken. I want to prevent the hyphenation of words at all cost, so I thought I could simply wrap all the individual words inside the caption into \mboxes. This would cause line breaks to be inserted between words, not inside of them.

But of course, I don’t want to change my usage of \chapter. That is, I do not want to write \chapter{\mbox{Some} \mbox{chapter}}. Instead, I wanted to handle this by redefining \chapter (well, using [explicit]titlesec actually).

My idea was to create a list parser using etoolbox that separates the words on whitespace and wraps the words in mboxes. Conceptually, this is extremely simple:

  \DeclareListParser{\dospacelist}{ }

  {\thechapter\ }

Not very surprisingly, this doesn’t work. I also tried changing the catcode of space to 11 in the mboxed command inside a group but this didn’t work either.

Is it even possible to write the mboxed macro in (La)TeX? How should this look like?

Increased difficulty (for extra points): The captions can also contain macros themselves, for example, one of my chapters is defined as


… because the \cpp command, which us a pretty-printed version of the string “C++”, doesn’t work in PDF labels.

Best Answer

Based on the \zap@space macro from source2e. It uses \fbox instead of \hbox for demonstration purposes.


  {\thechapter\ }

    \@mboxed#1 \@empty
\def\@mboxed#1 #2{%
   \fbox{#1}\space  % fbox here to have a visual test
   \ifx #2\@empty\else
%    \orig@chapter[#1]{\mboxed{#2}}%


\chapter{The Test of the code}

\mboxed{This should be tested}

\chapter{I like to thank you for this easy question}

\chapter{Also works with macros like \texorpdfstring{\cpp}{C++} very well}

\chapter{More difficult stuff should be wrapped in double braces {{A\empty{} B}} to hide the spaces!}

Related Question