6

In the following example,

\documentclass{article}
\usepackage{xstring}
\newcommand\foo[1]{\StrSubstitute{#1}{love}{hate}}

\begin{document}
 \section*{\foo{I love Mondays}}
\end{document}

if I remove the * from \section* the code stops compiling.

  1. What is the trick that makes \section* work ok with \StrSubstitute but not \section?
  2. Is there a workaround to include the command \foo in a \section header too?
6

Remember, section headings are also used for the table of contents, thus expanded and written to the .toc file. Use \protect to prevent the early expansion of \foo:

\section{\protect\foo{I love Mondays}}

Alternatively use the optional argument to fix it:

\section[]{\foo{I love Mondays}}

Have a look at Fragile and Robust commands for explanation.

You can define the command to be robust, avoiding such problems from the beginning:

\DeclareRobustCommand\foo[1]{\StrSubstitute{#1}{love}{hate}}
2
  • thanks for the answer (and Herbert, too); but I still do not get why the same syntax works with \section*. Moreover, is there a way to modify either \section or \foo so that I can use the second syntax without a \protect or an optional argument? Jan 19 '11 at 21:05
  • 2
    @Federico: \section* doesn't create a table of contents entry, that's why id doesn't expand \foo writing it to the .toc file which causes the problem. You can make it robust by \DeclareRobustCommand. I'll edit my answer to add that.
    – Stefan Kottwitz
    Jan 19 '11 at 21:09
2

it is a moving argument:

  \section{\protect\foo{I love Mondays}}

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.