[Tex/LaTex] Iterate over space-separated list

foreachmacrosparsingtoken-lists

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:

\newcommand*\mboxed[1]{%
  \let\do\mbox
  \DeclareListParser{\dospacelist}{ }
  \dospacelist#1}

\titleformat{\chapter}
  {\sffamily\Huge}
  {\thechapter\ }
  {0pt}
  {\mboxed{#1}}

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

\chapter{{\texorpdfstring{\cpp}{C++}}

… 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.

\documentclass{book}
\usepackage[explicit]{titlesec}
\usepackage{hyperref}
\def\cpp{C++}

\titleformat{\chapter}
  {\sffamily\Huge}
  {\thechapter\ }
  {0pt}
  {\mboxed{#1}}


\makeatletter
\def\mboxed#1{%
    \@mboxed#1 \@empty
}
\def\@mboxed#1 #2{%
   \fbox{#1}\space  % fbox here to have a visual test
   \ifx #2\@empty\else
    \expandafter\@mboxed
   \fi
   #2%
}
%\let\orig@chapter\chapter
%\renewcommand*{\chapter}[2][]{%
%    \orig@chapter[#1]{\mboxed{#2}}%
%}%
\makeatother


\begin{document}

\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!}

\end{document}
Related Question